C++拷贝构造函数和赋值函数

本文详细讲解了C++中拷贝构造函数和赋值函数的使用场景,包括初始化对象、作为参数传递、返回值以及对象间赋值的过程。通过实例演示,展示了何时选择复制构造函数和赋值函数,以确保高效和正确地管理对象资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在定义一个类时,会默认生成拷贝构造函数和赋值

拷贝构造函数

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;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值