Copy constructor vs assignment operator in C++

本文通过代码示例详细解析C++中的CopyConstructor和AssignmentOperator,探讨它们在对象创建和赋值时的区别。通过禁用默认的拷贝构造和赋值操作符,强调了编译器的隐式行为,并提醒开发者注意对象复制的控制。
摘要由CSDN通过智能技术生成

从现有对象创建新对象时,是Copy Constructor。 当已初始化的对象从另一个现有对象中分配了新值时,是Assignment Operator。当然,看到这句话,你还是不懂.下面看一下代码

#include<iostream> 
#include<stdio.h> 

using namespace std; 

class Test 
{ 
	public: 
	Test() {} 
	Test(const Test &t) 
	{ 
		cout<<"Copy constructor called "<<endl; 
	} 
	
	Test& operator = (const Test &t) 
	{ 
		cout<<"Assignment operator called "<<endl; 
		return *this; 
	} 
}; 

// Driver code 
int main() 
{ 
	Test t1, t2; 
	t2 = t1; //这里是Assignmeng operator
	Test t3 = t1; //这里是copy constrctor
	getchar(); 
	return 0; 
} 

看到代码是不是清楚了些,不过你记得小时候这样的代码

#include<iostream> 
#include<stdio.h> 

using namespace std;

class Test
{
public:
	Test() {}
	int a = 0;
	
};

// Driver code 
int main()
{
	Test t1, t2;
	t1.a = 3;
	t2 = t1;
	cout << t2.a << endl;  //输出3
	Test t3 = t1;
	cout << t3.a << endl; //输出3
	getchar();
	return 0;
}

你没有写copy construct 怎么也会赋值上,这是因为编译器偷偷的给你把copy construct和assignment operator写上去了. 可以这样搞一下

#include<iostream> 
#include<stdio.h> 

using namespace std;

class Test
{
public:
	Test() {}
	int a = 0;
	Test(const Test &t) = delete;
	

	Test& operator = (const Test &t) = delete;
	
};

// Driver code 
int main()
{
	Test t1, t2;
	t1.a = 3;
	t2 = t1;  //编译错误
	cout << t2.a << endl;
	Test t3 = t1; //编译错误
	cout << t3.a << endl;
	getchar();
	return 0;
}

这样,就相当于你警告编译器不要多事.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值