- 论坛徽章:
- 0
|
- 1 #include <iostream>;
- 2 using namespace std;
- 3
- 4 class Point
- 5 {
- 6 private:
- 7 int x;
- 8 int y;
- 9 public:
- 10 int GetX(){return x;}
- 11 int GetY(){return y;}
- 12 void Assign(int xx=0,int yy=0)
- 13 {
- 14 x = xx;
- 15 y = yy;
- 16 }
- 17
- 18 Point(int xx=0,int yy=0)
- 19 {
- 20 x = xx;
- 21 y = yy;
- 22 }
- 23 Point(Point &p)
- 24 {
- 25 x = p.x;
- 26 y = p.y;
- 27 cout<<"copy constructor invoked"<<endl;
- 28 }
- 29 };
- 30
- 31 Point f(Point p)
- 32 {
- 33 p.Assign( 2*p.GetX() , 2*p.GetY() );
- 34
- 35 return p;
- 36 }
- 37
- 38 int main(void)
- 39 {
- 40 Point p1(2,3);
- 41 Point p2;
- 42 p2 = f(p1);
- 43
- 44
- 45 return 0;
- 46 }
复制代码
输出了两次“copy constructor invoked”。第42行p2 = f(p1),倘若把这句注释掉,就没有复制构造函数被调用了。我看书上说,复制构造函数有3种情况被调用:
1, A(B)这样的初始化;
2,象上边f(Point p),调用f()时的形参、实参结合;
3,象上边f(Point p),返回Point型的对象时。
这个小程序符合条款的2和3,所以输出了2次“copy constructor invoked”。似乎是正确的;然而,同样的小程序输出却很不一样:
- 1 #include <iostream>;
- 2 using namespace std;
- 3
- 4 class Point
- 5 {
- 6 private:
- 7 int x;
- 8 int y;
- 9 public:
- 10 Point(int xx=0,int yy=0){x=xx;y=yy;}
- 11 Point(Point& p1){
- 12 x = p1.x;
- 13 y = p1.y;
- 14 cout<<"copy constructor invoked"<<endl;
- 15 }
- 16
- 17 };
- 18
- 19 Point f()
- 20 {
- 21 Point tmp(32,33);
- 22 return tmp;
- 23 }
- 24
- 25 int main()
- 26 {
- 27 Point p1;
- 28 p1 = f();
- 29 return 0;
- 30 }
复制代码
这次没有参数传递,不符合第2条;却还有返回对象,依然符合第3条啊。可是运行时什么输出都没有。
还有,我是在书上看的,书上还为这3种情况各举了一个例子,就跟上面差不多。结果却不一样。我糊涂了,请朋友们帮帮忙吧,谢了谢了先  |
|