考察下面的程序。
#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();
class TPoint
{
public:
private:
int Y;
int X;
};
TPoint::TPoint()
{
};
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::TPoint(TPoint &p)
{
}
主函数一:
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;
}
{
}
void main()
{
}
运行结果:
执行了拷贝初始化函数!
执行了拷贝初始化函数!
//实参传给形参
ok
执行了拷贝初始化函数!
//R初始化匿名对象
执行了析构函数
//释放Q
执行了析构函数
//释放R
执行了析构函数
//释放匿名对象
P=30,55
执行了析构函数
执行了析构函数
执行了析构函数
执行了拷贝初始化函数!
ok
执行了拷贝初始化函数!
执行了析构函数
执行了析构函数
执行了析构函数
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;
}
运行结果:
TPoint f(TPoint &Q)
{
}
void main()
{
}
运行结果:
执行了拷贝初始化函数!
ok
执行了拷贝初始化函数!
//R初始化匿名对象
执行了析构函数
//释放R
执行了析构函数
//释放匿名对象
P=30,55
执行了析构函数
执行了析构函数
执行了析构函数
ok
执行了拷贝初始化函数!
执行了析构函数
执行了析构函数
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;
}
运行结果:
TPoint f(TPoint &Q)
{
}
void main()
{
}
运行结果:
执行了析构函数
//N=TPoint(2,2);释放匿名对象
ok
执行了拷贝初始化函数! //R初始化匿名对象
执行了析构函数
执行了析构函数
P=12,22
执行了析构函数
执行了析构函数
执行了析构函数
ok
执行了拷贝初始化函数!
执行了析构函数
执行了析构函数
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;
}
运行结果:
TPoint f(TPoint &Q)
{
}
void main()
{
}
运行结果:
ok
执行了拷贝初始化函数!
执行了拷贝初始化函数!
执行了析构函数
执行了析构函数
P=12,22
执行了析构函数
执行了析构函数
执行了析构函数
//说明N(TPoint(2,2))与N(2,2)的作用是一样的
执行了析构函数
P=12,22
执行了析构函数
执行了析构函数
执行了析构函数
//说明N(TPoint(2,2))与N(2,2)的作用是一样的
补充说明:对象初始化和赋值是不一样的,例如