C++ - 复制构造器 和 复制-赋值操作符 的 区别
2013-12-23 08:48
405 查看
C++ - 复制构造器 和 复制-赋值操作符 的 区别
分类: C++2013-11-1112:33 336人阅读 评论(0) 收藏 举报
C++Mystracopy
constructorcopy-assignment区别
复制构造器 和 复制-赋值操作符 的 区别
本文地址: /article/1384306.html复制构造器(copy constructor):定义新对象, 则调用复制构造器(constructor);
复制-赋值操作符(copy-assignment operator):没有定义新对象, 不会调用构造器;
注意一个语句, 只能使用一个方式, 并不是出现"=", 就一定调用复制-赋值操作符, 构造器有可能优先启用.
代码:
[cpp] view
plaincopy
#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构造器
}
输出:
[cpp] view
plaincopy
Hello girl, this is a copy constructor!
Hello girl, this is a copy-assignment operator!
Hello girl, this is a copy constructor!
相关文章推荐
- C++ - 复制构造器 和 复制-赋值操作符 的 区别
- C++ - 复制构造器 和 复制-赋值操作符 的 区别
- 2013级C++第7周(春)项目——深复制、友元、模板 【项目3-成员函数、友元函数和一般函数有区别】
- C++ 复制构造和赋值的区别
- C++的一大误区——深入解释直接初始化与复制初始化的区别
- C++的一大误区——深入解释直接初始化与复制初始化的区别
- C++的一大误区——深入解释直接初始化与复制初始化的区别
- C++的一大误区-深入理解直接初始化与复制初始化的区别
- C++直接初始化与复制初始化的区别深入解析
- C++的一大误区——深入解释直接初始化与复制初始化的区别
- c++ 构造器的copy(拷贝), assignment(复制)
- c++复制函数的区别
- C++的一大误区——深入解释直接初始化与复制初始化的区别
- C++的对象复制构造函数与赋值操作符重载的区别小结
- C++常规指针类(浅复制),智能指针类(计数类),值行类(深复制) 区别
- C++ - 复制(copy) 和 虚复制(virtual copy) 的 区别
- C++ 复制构造和赋值操作符调用
- C++ - 复制(copy) 和 虚复制(virtual copy) 的 区别
- C++的一大误区——深入解释直接初始化与复制初始化的区别