代码如下,按理应该调用复制运算符啊,为何却是调用了复制构造函数:
1 #include <iostream>
2 using std::cout;
3 using std::endl;
4 using std::string;
5
6 class Test
7 {
8 public:
9 Test()
10 {
11 cout << "The default constructor is called!" << endl;
12 }
13
14 Test(const Test &rhs)
15 :strTest(rhs.strTest)
16 {
17 cout << "Test copying function is called!" << endl;
18 }
19
20 Test & operator=(const Test &rhs)
21 {
22 strTest = rhs.strTest;
23 cout << "Test copy assignment function is called!" << endl;
24 return *this;
25 }
26
27 private:
28 string strTest;
29 };
30
31 int main()
32 {
33 Test myTestA;
34 Test myTestB = myTestA;
35
36 return 0;
37 }
编译后的运行结果为:
1 [tortoise@sea temp]$ ./test
2 The default constructor is called!
3 Test copying function is called!
4 [tortoise@sea temp]$