C++中的复制构造函数与赋值运算符对比

Copy Constructor vs Assignment Operator in C++

Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them:

复制构造函数和赋值运算符相似,因为它们都用于使用另一个对象初始化一个对象。但是,它们之间有一些基本的区别:

Copy constructorAssignment operator
It is called when a new object is created from an existing object, as a copy of the existing objectThis operator is called when an already initialized object is assigned a new value from another existing object.
It creates a separate memory block for the new object.It does not create a separate memory block or new memory space.
It is an overloaded constructor.It is a bitwise operator.
C++ compiler implicitly provides a copy constructor, if no copy constructor is defined in the class.A bitwise copy gets created, if the Assignment operator is not overloaded.
Syntax:
className(cont className &obj)
{body}
Syntax:
className obj1, obj2;
obj2 = obj1;
复制构造函数赋值运算符
当从现有对象创建新对象时调用它,作为现有对象的副本当已经初始化的对象从另一个现有对象中分配了新值时,将调用此运算符。
它为新对象创建一个单独的内存块。它不会创建单独的内存块或新的内存空间。
它是一个重载的构造函数。它是一个位运算符。
如果类中没有定义复制构造函数,C++ 编译器会隐式提供复制构造函数。如果赋值运算符未重载,则会创建按位副本。
句法:
className(cont className &obj)
{body}
句法:
className obj1, obj2;
obj2 = obj1;

Consider the following C++ program.


// CPP Program to demonstrate the use of copy constructor
// and 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;
	Test t3 = t1;
	getchar();
	return 0;
}

Output

Assignment operator called 
Copy constructor called 

Explanation: Here, t2 = t1; calls the assignment operator, same as t2.operator=(t1); and Test t3 = t1; calls the copy constructor, same as Test t3(t1);

解释:t2 = t1; 调用了赋值运算符,与t2.operator=(t1); 是相同的。Test t3 = t1; 调用了复制构造函数,与 Test t3(t1); 是相同的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值