关于析构函数和拷贝初始化函数

考察下面的程序。
#include <iostream.h>
class TPoint 
{
public:
  int Ycoord();
  int Xcoord();
  TPoint(TPoint &p);
  TPoint();
  TPoint(int x,int y){X=x;Y=y;}
  virtual ~TPoint();
private:
  int Y;
  int X;
};
TPoint::TPoint()
{
}
TPoint::~TPoint()
{
    cout<<"执行了析构函数\n";
}
int TPoint::Xcoord()
{
  return X;
}
int TPoint::Ycoord()
{
      return Y;
}
TPoint::TPoint(TPoint &p)
{
  X=p.X;
  Y=p.Y;
  cout<<"执行了拷贝初始化函数!\n";
}
 
主函数一:
TPoint f(TPoint Q)
{
  cout<<"ok\n";
  int x,y;
  x=Q.Xcoord()+10;
  y=Q.Ycoord()+20;
  TPoint R(x,y);
  return R;
}
void main()
{
    TPoint M(20,35),P(10,10);
    TPoint N=M;      //这里执行了拷贝初始化函数,相当于N(M)  ,如果在下一句赋
    P=f(N);              //则不会执行初始化的函数
    cout<<"P="<<P.Xcoord()<<","<<P.Ycoord()<<endl;
}
运行结果:
执行了拷贝初始化函数!   
执行了拷贝初始化函数!    //实参传给形参
ok
执行了拷贝初始化函数!    //R初始化匿名对象
执行了析构函数      //释放Q
执行了析构函数      //释放R
执行了析构函数      //释放匿名对象
P=30,55
执行了析构函数
执行了析构函数
执行了析构函数
主函数2:
#include "TPoint.h"
TPoint f(TPoint &Q)
{
  cout<<"ok\n";
  int x,y;
  x=Q.Xcoord()+10;
  y=Q.Ycoord()+20;
  TPoint R(x,y);
  return R;
}
void main()
{
    TPoint M(20,35),P(10,10);
    TPoint N=M;
    P=f(N);
    cout<<"P="<<P.Xcoord()<<","<<P.Ycoord()<<endl;
}
运行结果:
执行了拷贝初始化函数!
ok
执行了拷贝初始化函数!    //R初始化匿名对象
执行了析构函数                //释放R
执行了析构函数              //释放匿名对象
P=30,55
执行了析构函数
执行了析构函数
执行了析构函数
主函数3:
#include "TPoint.h"
TPoint f(TPoint &Q)
{
  cout<<"ok\n";
  int x,y;
  x=Q.Xcoord()+10;
  y=Q.Ycoord()+20;
  TPoint R(x,y);
  return R;
}
void main()
{
    TPoint M(20,35),P(10,10);
    TPoint N;
    N=TPoint(2,2);
    P=f(N);
    cout<<"P="<<P.Xcoord()<<","<<P.Ycoord()<<endl;
}
运行结果:
执行了析构函数    //N=TPoint(2,2);释放匿名对象
ok
执行了拷贝初始化函数!  //R初始化匿名对象
执行了析构函数
执行了析构函数
P=12,22
执行了析构函数
执行了析构函数
执行了析构函数
 
 
主函数4:
#include "TPoint.h"
TPoint f(TPoint &Q)
{
  cout<<"ok\n";
  int x,y;
  x=Q.Xcoord()+10;
  y=Q.Ycoord()+20;
  TPoint R(x,y);
  return R;
}
void main()
{
    TPoint M(20,35),P(10,10);
    TPoint N(TPoint(2,2));
    P=f(N);
    cout<<"P="<<P.Xcoord()<<","<<P.Ycoord()<<endl;
}
运行结果:
ok
执行了拷贝初始化函数!   
执行了析构函数
执行了析构函数
P=12,22
执行了析构函数
执行了析构函数
执行了析构函数
//说明N(TPoint(2,2))与N(2,2)的作用是一样的
补充说明:对象初始化和赋值是不一样的,例如
  TPoint M[2]={TPoint(20,50)}; 
  M[1]=TPoint(20,10);    //执行这一句的时候,要先赋给匿名对象,然后删除匿名对象
 
 
 
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值