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

来源:互联网 发布:文员office办公软件 编辑:程序博客网 时间:2024/06/14 05:39

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

 

本文地址: 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!