现在的位置: 首页 > 综合 > 正文

copy构造函数的易错点

2013年06月26日 ⁄ 综合 ⁄ 共 665字 ⁄ 字号 评论关闭
 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 }

 

 运行结果: 

 

抱歉!评论已关闭.