0
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 的,从哪里来的?

4

2 回答 2

2

从声明中——

int test::n=0; 

' ::' 称为范围解析运算符。这个操作符在这里用来初始化静态字段n,而不是类

于 2015-05-02T20:05:55.893 回答
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--; };

事实上,这个静态变量起到了统计类的活动对象的作用。

因此,您主要定义了名称为 a 的类的对象

test a;

每次定义对象时,都会调用类的构造函数。因此 n 增加并等于 1。 Adter 定义了 5 个对象的数组

test b[5];  

n 等于 6。

动态分配一个对象后

test * c = new test;

n 等于 7。

明确删除后

delete c;

n 再次变为等于 6,因为调用的析构函数减少了 n。

于 2015-05-02T20:12:01.830 回答