您的位置:首页 > 编程语言 > C语言/C++

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

2013-11-11 12:33 281 查看

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

 
本文地址: 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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息