很久没看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