1 #include <iostream> 2 using namespace std; 3 4 class Test 5 { 6 public: 7 Test(int n = 1) 8 { 9 val = n; 10 cout << "Con." << endl; 11 } 12 13 Test(const Test& t) 14 { 15 val = t.val; 16 cout << "Copy con." << endl; 17 } 18 19 Test& operator=(Test& t) 20 { 21 val = t.val; 22 cout << "Assignment." << endl; 23 return *this; 24 } 25 26 private: 27 int val; 28 }; 29 30 void func1(Test t) 31 { 32 } 33 34 Test func2() 35 { 36 Test t; 37 return t; 38 } 39 40 void main() 41 { 42 Test t1(1); 43 44 Test t2 = t1; // ① 45 46 Test t3; 47 t3 = t1; 48 49 func1(t2); // ② 50 51 t3 = func2(); // ③ 52 }
运行结果:
Con.
Copy con.[①创建并初始化对象t2,调用复制构造函数]
Con.
Assignment.
Copy con.[②实参以传值方式初始化形参,调用复制构造函数]
Con.
Copy con.[③调用复制构造函数简历临时对象,作为函数返回值]
Assignment.
原文:http://www.cnblogs.com/codingthings/p/4294594.html