gpt4 book ai didi

c++ - 如何访问类对象的每个实例的静态变量值

转载 作者:行者123 更新时间:2023-11-28 01:51:04 24 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
this->objectCount++;
}

double Volume() {
return length * breadth * height;
}

static int getID()
{
return objectCount;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
cout << "Box1 ID: " << Box1.getID() << endl;
cout << "Box2 ID: " << Box2.getID() << endl;

return 0;
}

如何访问“Box1”和“Box2”的 objectCount。 “Box1”的 objectCount 应该为 1,而“Box2”仍为 2。例如

它打印:

Constructor called.
Constructor called.
Total objects: 2
Box1 ID: 2
Box2 ID: 2

代替:

Constructor called.
Constructor called.
Total objects: 2
Box1 ID: 1
Box2 ID: 2

最佳答案

类只有一个objectCount。根据定义,这就是 static 类成员。

您需要做的是向类中添加一个非静态成员,并在构造函数中对其进行初始化。

 static int objectCount;
int my_objectCount;

// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0)
: my_objectCount(++objectCount)
{
// ...
}

然后,对于类的第一个实例,my_objectCount 将为 1,对于第二个实例为 2,依此类推。

关于c++ - 如何访问类对象的每个实例的静态变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43015830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com