struct obj1
{
static int counter = 0;
obj1() {counter++;}
};
struct obj2
{
obj1* o1 = nullptr;
};
struct obj3
{
obj2* o2 = nullptr;
};
int main()
{
obj3 o3;
o3.o2 = new obj2[3];
o3.o2[0].o1 = new obj1[1];
o3.o2[1].o1 = new obj1[4];
o3.o2[2].o1 = new obj1[3];
}
o1的每个数组都有自己的静态计数器,或者所有对象o1是否共享同一个计数器?为什么?
答案 0 :(得分:0)
我们可以使用 static 关键字定义类成员静态。当我们将类的成员声明为static时,意味着无论创建了多少个类的对象,都只有一个静态成员的副本。
静态成员由类的所有对象共享。如果没有其他初始化,则在创建第一个对象时,所有静态数据都将初始化为零。我们不能将它放在类定义中,但它可以在类外部初始化,如下例所示,通过重新声明静态变量,使用范围解析运算符::来标识它属于哪个类。
让我们尝试以下示例来理解静态数据成员的概念:
#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
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
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;
return 0;
}
编译并执行上述代码时,会产生以下结果:
Constructor called.
Constructor called.
Total objects: 2
因此,所有static
个对象的o1
计数器都相同
来源:http://www.tutorialspoint.com/cplusplus/cpp_static_members.htm
希望这有帮助
答案 1 :(得分:0)
只有一个变量。你必须在你的计划中的某个地方:
int obj1::counter;
是该变量的定义。 (课堂声明只是声明)。
关于“为什么”,这就是static
在这里的含义。没有语言结构用于拥有在对象之间共享的变量,而只包含属于数组成员的变量。如果那就是你想要的那么你就必须明确地创建一个包含数组和变量的类,或者其他什么。
如果您只想跟踪数组中有多少项,请使用std::array
或std::vector
之类的容器,而不是原始指针。