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

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

2013-12-23 08:48 405 查看


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

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