why should the parameter in copy construction be a reference

if not, it will lead to an endless loop!!!

 1 # include<iostream>
 2 using namespace std;
 3 class A
 4 {
 5 public:
 6     int var;
 7 
 8     A():var(0){}
 9 
10     A(A &a){this->var = a.var;cout << "copy\n";}
11 
12     void operator=(A b){cout << "assign\n";}
13 
14     A func(A a){return a;}
15     //A func(A &a){ return a; }
16     
17     ~A(){cout << "destroy\n";}
18 };
19 
20 int main()
21 {
22     A a, b, c;
23     b.var = 5;
24     a = b;
25     cout << "\n";
26     c = a.func(b);
27     system("pause");
28 }
View Code

 update:  1) class a = b; 2) a=c;

1) will call copy constructor, because a havent be constructed;

2) will call assignemnt constructor, because a has it's mem room, we should just modify it's value

posted @ 2017-02-27 12:32  HEIS老妖  阅读(128)  评论(0编辑  收藏  举报