geeksforgeeks-056-拷贝构造函数 vs 赋值操作符

如下程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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 ()
{
Test t1, t2;
t2 = t1;
Test t3 = t1;
getchar();
return 0;
}

Output:

1
2
Assignment operator called
Copy constructor called

当一个对象根据一个已存在的对象被创建时,拷贝构造函数被调用。
当一个已经存在的对象被另一个已经存在的对象赋予新值时,赋值操作符被调用。

1
2
t2 = t1;  
Test t3 = t1; // calls copy constructor, same as "Test t3(t1);"