MOOC清华《面向对象程序设计》第3章:static静态成员实验
2017-08-18 17:54
309 查看
#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!这是为什么呢?
相关文章推荐
- MOOC清华《面向对象程序设计》第3章:赋值运算符重载实验
- MOOC清华《面向对象程序设计》第3章:流运算符重载实验
- MOOC清华《面向对象程序设计》第3章:移动构造函数实验
- MOOC清华《面向对象程序设计》第3章编程题第1题:重载函数运算符以封装排序算法
- MOOC清华《面向对象程序设计》第3章:下标运算符重载实验
- MOOC清华《面向对象程序设计》第3章:前缀/后缀运算符重载实验
- MOOC清华《面向对象程序设计》第3章编程题第2题:重载下标运算符以统计分段人数
- MOOC清华《面向对象程序设计》第3章:const常量成员实验
- MOOC清华《面向对象程序设计》第3章:对象组合实验
- MOOC清华《面向对象程序设计》第3章:拷贝构造函数实验
- MOOC清华《面向对象程序设计》第2章:私有成员与公有成员不可同名实验
- MOOC清华《VC++面向对象与可视化程序设计》第3章:Windows文本-例(1)文本显示示例程序
- MOOC清华《面向对象程序设计》第4章:继承基类构造函数实验
- MOOC清华《面向对象程序设计》第4章:函数模板的特化实验
- MOOC清华《面向对象程序设计》第7章:负载监视器的设计v2.0(采用基于模板的策略模式)
- MOOC清华《VC++面向对象与可视化程序设计》第3章:Windows文本-例(3)动态文本的显示
- MOOC清华《面向对象程序设计》第1章:源文件的拆分与多文件的编译运行
- MOOC清华《面向对象程序设计》第4章:类模板的特化实验
- MOOC清华《VC++面向对象与可视化程序设计》第3章:Windows文本-例(4)竖排的古诗
- MOOC清华《程序设计基础》第3章:谁做的好事(顺序枚举)