1 #include <iostream>
2 using namespace std;
3
4 class Base{
5 public:
6 Base(int val = 0): ival(val)
7 {
8 cout << "constructure" << endl;
9 }
10 Base(const Base& rhs) //注意形参的const
11 {
12 cout << "copy constructure" << endl;
13 }
14 Base& operator=(const Base& rhs) //注意返回的是引用,注意形参的const
15 {
16 this->ival = rhs.ival;
17 cout << "copy assignment operator" << endl;
18 return *this;
19 }
20 private:
21 int ival;
22 };
23
24 void main()
25 {
26 Base b1;
27 Base b2 = b1; //调用copy构造函数
28 Base b3;
29 b3 = b1;
30 int ival;
31 cin >> ival;
32 }
2 using namespace std;
3
4 class Base{
5 public:
6 Base(int val = 0): ival(val)
7 {
8 cout << "constructure" << endl;
9 }
10 Base(const Base& rhs) //注意形参的const
11 {
12 cout << "copy constructure" << endl;
13 }
14 Base& operator=(const Base& rhs) //注意返回的是引用,注意形参的const
15 {
16 this->ival = rhs.ival;
17 cout << "copy assignment operator" << endl;
18 return *this;
19 }
20 private:
21 int ival;
22 };
23
24 void main()
25 {
26 Base b1;
27 Base b2 = b1; //调用copy构造函数
28 Base b3;
29 b3 = b1;
30 int ival;
31 cin >> ival;
32 }
运行结果: