C++运算符重载(2) - 拷贝构造vs赋值操作符
2015-05-26 09:29
330 查看
参考下面的程序:
Assignment operator called
Copy constructor called
当使用一个已存在对象来创建新的对象时,就会调用拷贝构造函数。而赋值操作符用于将一个已存在对象赋值给另外一个已存在对象。
t2 = t1; // 调用赋值操作符, 相当于"t2.operator=(t1);"
Test t3 = t1; // 调用拷贝构造函数,相当于"Test t3(t1);"
参考:
http://en.wikipedia.org/wiki/Copy_constructor
#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
相关文章推荐
- string类构造、拷贝构造、赋值、操作符函数实现及注意事项
- string类构造、拷贝构造、赋值、操作符函数实现及注意事项
- C++ 对象构造, 拷贝, 赋值和隐式类型转换总结
- 模板拷贝构造与赋值的不对称
- STL程序设计实践三:剖析STL容器的拷贝构造和赋值特性
- 继承中构造、析构 与 拷贝构造、赋值中的调用区别
- C++中的拷贝构造,赋值和移动构造
- 拷贝构造、赋值构造、深拷贝、浅拷贝、位拷贝、值拷贝
- 普通构造、拷贝构造、对象赋值操作运算符重载的代码实例
- 请用c++ 实现stl中的string类,实现构造,拷贝构造,析构,赋值,比较,字符串相加,获取长度及子串等功能。
- 构造、拷贝(复制)构造、赋值构造以及析构
- C++类中的4个特殊函数 - 缺省构造函数、拷贝构造函数、拷贝赋值操作符和析构函数
- 构造、拷贝构造、赋值
- 20140413 拷贝、赋值构造 变量分配确定时期 子类指针与父类指针转化 虚函数
- 构造函数,复制构造函数与拷贝赋值操作符
- 拷贝构造-赋值构造-深拷贝-浅拷贝
- TTCN3新执行器系列-如何最小化类的成员函数(对拷贝构造和赋值操作函数的反思)
- GeekBand学习笔记:C++三大函数:拷贝构造、拷贝赋值、析构函数
- C++【拷贝构造】和【拷贝赋值】(实现自定义的string类)
- 【Boost】系列04:实用技巧之禁止类拷贝构造和赋值