在定义一个类时,会默认生成拷贝构造函数和赋值
拷贝构造函数
CObject(const CObject& oOBJ);
CObject::CObject(const CObject &oOBJ)
{
//process data
}
什么时候用拷贝构造函数:
赋值函数
CObject& operator=(const CObject& oOBJ);
CObject& CObject::operator=(const CObject &oOBJ)
{
cout<<"This is operator = function."<<endl;
if (this != &oOBJ)
{
cout << "process data assign." << endl;
}
return *this;
}
什么时候用赋值函数:
示例
#include <iostream>
using namespace std;
class CObject
{
public:
CObject();
~CObject();
CObject(const CObject& oOBJ);
CObject& operator=(const CObject& oOBJ);
};
CObject::CObject()
{
cout<<"This is construct function."<<endl;
}
CObject::~CObject()
{
cout<<"This is destruct function."<<endl;
}
CObject::CObject(const CObject &oOBJ)
{
cout<<"This is copy-construct function."<<endl;
}
CObject& CObject::operator=(const CObject &oOBJ)
{
cout<<"This is operator = function."<<endl;
if (this != &oOBJ)
{
cout << "process data assign." << endl;
}
return *this;
}
void test1(CObject oObj)
{
}
CObject test2(CObject oObj)
{
return oObj;
}
int main(int argc, char* argv[])
{
cout<<"**************use construct create oObjA**************************" << endl;
CObject oObjA;
cout << endl;
cout << "**************use copy-construct create oObjB**************************" << endl;
CObject oObjB = oObjA;
cout << endl;
cout << "**************use construct create oObjc**************************" << endl;
CObject oObjC;
cout << "**************copy data from oObjA to oObjc**************************" << endl;
oObjC = oObjA;
cout << endl;
cout << "**************use copy-construct in parameter**************************" << endl;
test1(oObjB);
cout << endl;
cout << "**************use copy-construct in return**************************" << endl;
test2(oObjB);
cout << endl;
cout << "**************end **************************" << endl;
return 0;
}
运行结果:
|