C++类默认函数

很久没看C++了,遇到了一道C++类相关试题,输出结果让我有点诧异,想了下,终于找到原因。

 

原题为:

#include <iostream.h>
class cEmpty
{
  public:
  cEmpty() // 缺省构造函数
  {
        cout<<"default constructor"<<endl;
  }
  cEmpty(int data) // 带参构造函数
  {    	
		cout<<"constructor variable ="<<data<<endl;	
  }    
  ~cEmpty() // 析构函数
  {
        cout<<"destructor"<<endl;
  }
};

cEmpty empty_test(cEmpty ce)
{  
  //cout<<"empty_test"<<endl;
  return ce;
}
int main()
{
  cEmpty ce1 = empty_test(9);
  cEmpty ce2 = empty_test(ce1); 
  return 1;
}

 

输出结果:
constructor variable =9
destructor
destructor
destructor
destructor

 

为什么只构造一次,却析构了4次呢?
当把C++类默认函数加上之后,答案水落石出。

 

#includ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值