C++ - 复制构造器 和 复制-赋值操作符 的 区别

复制构造器 和 复制-赋值操作符 的 区别

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/15336889 

 

复制构造器(copy constructor):定义新对象, 则调用复制构造器(constructor);

复制-赋值操作符(copy-assignment operator):没有定义新对象, 不会调用构造器;

注意一个语句, 只能使用一个方式, 并不是出现"=", 就一定调用复制-赋值操作符, 构造器有可能优先启用.

代码:

#include <iostream>

class Widget {
public:
	Widget () = default;
	Widget (const Widget& rhs) {
		std::cout << "Hello girl, this is a copy constructor! " << std::endl;
	}
	Widget& operator= (const Widget& rhs) {
		std::cout << "Hello girl, this is a copy-assignment operator! " << std::endl;
		return *this;
	}
};

int main (void) {
	Widget w1;
	Widget w2(w1); //使用copy构造器
	w1 = w2; //使用copy-assignment操作符
	Widget w3 = w2; //使用copy构造器
}


输出:

Hello girl, this is a copy constructor! 
Hello girl, this is a copy-assignment operator! 
Hello girl, this is a copy constructor! 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值