Copy constructor vs assignment operator in C++
Difficulty Level: Rookie
Consider the following C++ program.
1 #include<iostream>
2 #include<stdio.h>
3
4 using namespace std;
5
6 class Test
7 {
8 public:
9 Test()
10 {
11 }
12 Test(const Test &t)
13 {
14 cout<<"Copy constructor called "<<endl;
15 }
16 Test& operator = (const Test &t) //仅仅为测试
17 {
18 cout<<"Assignment operator called "<<endl;
19 return *this;
20 }
21 };
22
23 int main()
24 {
25 Test t1, t2;
26 t2 = t1;
27 Test t3 = t1;
28 getchar();
29 return 0;
30 }
Output:
Assignment operator called
Copy constructor called
Copy constructor is called when a new object is created from an existing object, as a copy of the existing object (see this G-Fact).
And assignment operator is called when an already initialized object is assigned a new value from another existing object.
t2 = t1; // calls assignment operator, same as "t2.operator=(t1);"
Test t3 = t1; // calls copy constructor, same as "Test t3(t1);"
References:http://en.wikipedia.org/wiki/Copy_constructor
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 21:23:27
最新文章
- 03.SQLServer性能优化之---存储优化系列
- HTML+CSS代码橙色导航菜单
- AKKA(一)认知AKKA
- 100个Github上Android开源库
- 敏捷软件开发:原则、模式与实践——第8章 SRP:单一职责原则
- stl中双向队列用法
- iOS 网络与多线程--4.同步Post方式的网络请求
- C#对数字添加逗号,千分位
- MongoDB学习(翻译2)
- XP_CMDSHELL 执行命令添加 windows 用户的方法
- LeetCode算法题-Factorial Trailing Zeroes(Java实现)
- socket基础编程-1
- openstack学习-创建一台云主机(七)
- Loadrunner11的安装方法和破解
- java引用类型简述
- 前端 HTML标签属性
- ubuntu 安装 android studio
- 聊一聊PV和并发、以及计算web服务器的数量的方法
- lambda续集——1
- linux取随机数shell版本