MOOC清华《面向对象程序设计》第3章:static静态成员实验

#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!这是为什么呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值