拷贝构造函数的析构问题

下列程序的运行结果是                   

#include <iostream.h>

class point

{  int x,y;

public:

     point(int a,int b)

     {x=a;y=b;

      cout<<"calling the constructor function."<<endl;

     }

     point(point &p);

     friend point move(point q);

     ~point(){cout<<"calling the destructor function.\n";}

     int getx()      {return x;}

     int gety()     {return y;}

};

point::point(point &p)

{x=p.x;  y=p.y;

 cout<<"calling the copy_initialization constructor function.\n";

}

point move(point q)

{cout<<"OK!\n";

 int i,j;

 i=q.x+10;

 j=q.y+20;

 point r(i,j);

 return r;

}

void main()

{ point m(15,40),p(0,0);

  point n(m);

  p=move(n);

  cout<<"p="<<p.getx()<<","<<p.gety()<<endl;

}

答案:

calling the constructor function.

calling the constructor function.

calling the copy_initialization constructor function.

calling the copy_initialization constructor function.

OK

calling the constructor function.

calling the copy_initialization constructor function.

calling the destructor function.

calling the destructor function.

calling the destructor function.

P=25,60

calling the destructor function.

calling the destructor function.

calling the destructor function.

说明:

1构造函数执行三次,分别初始化主函数中的对象mpmove函数中的对象r

2)拷贝构造函数共执行了三次。第一次,初始化对象n;第二次在调用函数move()时,实参n给形参q进行初始化;第三次是执行函数movereturn r;语句时,系统用r初始化一个临时对象时使用了拷贝构造函数。

3)析构函数执行了六次。在退出函数move时释放对象rq共调用二次;返回主函数后,临时对象赋值给对象p后,释放临时对象又调用一次析构函数;最后退出整个程序时释放对象mnp调用三次。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值