【问题标题】:Declaring class as integer将类声明为整数
【发布时间】:2015-07-12 11:09:39
【问题描述】:
class test {
public:
static int n;
test () { n++; };
~test () { n--; };
};
int test::n=0; //<----what is this step called? how can a class be declared as an integer?
int main () {
test a;
test b[5]; // I'm not sure what is going on here..is it an array?
test * c = new test;
cout << a.n << endl;
delete c;
cout << test::n << endl;
}
其次,输出是 7,6 我不明白它是怎么得到 7 的,从哪里来的?
【问题讨论】:
标签:
c++
class
initialization
colon
scope-resolution
【解决方案1】:
静态数据成员在类中声明。它们是在类之外定义的。
因此在类定义中
class test {
public:
static int n;
test () { n++; };
~test () { n--; };
};
记录
static int n;
只声明 n。您需要定义它,即为其分配内存。
还有这个
int test::n=0;
是它的定义。 test::n 是变量的限定名称,表示 n 属于类 test。
在构造类的对象时根据类定义增加这个静态变量
test () { n++; };
当一个对象被破坏时,这个静态变量会减少
~test () { n--; };
其实这个静态变量的作用是统计类的存活对象。
因此,您在 main 中定义了名为 a 的类的对象
test a;
每次定义对象时,都会调用类的构造函数。因此 n 增加并等于 1。
Adter 定义 5 个对象的数组
test b[5];
n 等于 6。
动态分配一个对象后
test * c = new test;
n 等于 7。
显式删除后
delete c;
n 再次变为等于 6,因为调用的析构函数减少了 n。
【解决方案2】:
来自声明-
int test::n=0;
'::' 称为范围解析运算符。这个操作符在这里是用来初始化静态字段n,而不是类