#include <iostream>
using namespace std;
class Test{
static int count;
public:
Test() { count++; }
~Test() { count--; }
static int how_many() { return count; }
};
int Test::count = 0;
void print(Test t){
cout << "in print(), Test#: " << t.how_many() << endl;
}
int main(){
Test t1;
cout << "Test#: " << Test::how_many() << endl;
Test t2 = t1;
cout << "Test#: " << Test::how_many() << endl;
print(t2);
cout << "Test#: " << t1.how_many() << ", "
<< t2.how_many() << endl;
return 0;
}
为什么对象t1和t2都存在的情况下,count却变成0了?析构函数在这两个对象中都已经调用了吗?清华徐明星老师在视频中讲解的原因是:类Test的定义中没有定义拷贝构造函数,所以在新的对象产生的时候,新对象并没有被统计进去,漏算了一些值。于是乎,我加入了一条拷贝构造函数语句,代码如下:
#include <iostream>
using namespace std;
class Test{
static int count;
public:
Test() { count++; }
Test(const Test& src) {
count = src.count; //测试一无用
//count++; //这个更加荒谬
cout << "Test(const Test&)" << endl;
}
~Test() { count--; }
static int how_many() { return count; }
};
int Test::count = 0;
void print(Test t){
cout << "in print(), Test#: " << t.how_many() << endl;
}
int main(){
Test t1;
cout << "Test#: " << Test::how_many() << endl;
Test t2 = t1;
cout << "Test#: " << Test::how_many() << endl;
print(t2);
cout << "Test#: " << t1.how_many() << ", "
<< t2.how_many() << endl;
return 0;
}
咦?运行结果最后一行依然是两个0!这是为什么呢?