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

C++运算符重载(2) - 拷贝构造vs赋值操作符

2015-05-26 09:29 330 查看
参考下面的程序:

#include<iostream>
#include<stdio.h>

using namespace std;

class Test
{
public:
Test() {}
Test(const Test &t)
{
cout<<"Copy constructor called "<<endl;
}
Test& operator = (const Test &t)
{
cout<<"Assignment operator called "<<endl;
}
};

int main()
{
Test t1, t2;
t2 = t1;
Test t3 = t1;
getchar();
return 0;
}
输出:

Assignment operator called

Copy constructor called

当使用一个已存在对象来创建新的对象时,就会调用拷贝构造函数。而赋值操作符用于将一个已存在对象赋值给另外一个已存在对象。

t2 = t1; // 调用赋值操作符, 相当于"t2.operator=(t1);"

Test t3 = t1; // 调用拷贝构造函数,相当于"Test t3(t1);"

参考:
http://en.wikipedia.org/wiki/Copy_constructor
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐