很久没看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++类默认函数加上之后,答案水落石出。
#include <iostream.h>
class cEmpty
{
public:
cEmpty() // 缺省构造函数
{
cout<<"default constructor"<<endl;
}
cEmpty(int data) // 带参构造函数
{
cout<<"constructor variable ="<<data<<endl;
}
cEmpty( const cEmpty& ) // 拷贝构造函数
{
cout<<"copy constructor"<<endl;
}
~cEmpty() // 析构函数
{
cout<<"destructor"<<endl;
}
cEmpty& operator=( const cEmpty& ) // 赋值运算符
{
cout<<"assignment constructor"<<endl;
}
cEmpty* operator&() // 取址运算符
{
cout<<"get address constructor"<<endl;
}
const cEmpty* operator&() const // 取址运算符 const
{
cout<<"get address constructor const"<<endl;
}
};
cEmpty empty_test(cEmpty ce)
{
//cout<<"empty_test"<<endl;
return ce;
}
int main()
{
cEmpty ce1 = empty_test(9);
cEmpty ce2 = empty_test(ce1);
//cEmpty obj1;//缺省构造函数
//cEmpty obj2;
//obj1=obj2;//赋值运算符
//&obj2;//取址运算符
//cEmpty obj3(obj1);//拷贝构造函数
//cEmpty const obj4(obj1);
//&obj4;//取址运算符 const
return 1;
}
输出结果过为:
constructor variable =9
copy constructor
destructor
copy constructor
copy constructor
destructor
destructor
destructor
原来是因为调用了3次拷贝构造函数,拷贝构造函数在原题中被隐藏,所以没有打印。