拷贝初始化构造函数:
1、函数名同类名,也是一种构造函数,并且不被指定返回类型。
2、函数只有一个参数,并且是对某个对象的引用。
3、每个类都必须有一个拷贝初始化构造函数:
<类名>::<拷贝初始化构造函数名>(const<类名>&<引用名>)
以下代码放在名为tpoint1.h的头文件当中
class TPoint
{
public:
TPoint(int x, int y){X=x; Y=y;}
TPoint(TPoint & p);
~TPoint(){cout<<"Destructor Called.\n";}
int Xcoord(){return X;}
int Ycoord(){return Y;}
private:
int X, Y;
};
TPoint::TPoint(TPoint & p)
{
X=p.X;
Y=p.Y;
cout<<"Copy_initialization Constructor Called.\n";
}
以下放在另一文件当中
#include<iostream.h>
#include"tpoint1.h"
TPoint f(TPoint Q);
void main()
{
TPoint M(20,30),P(0,0);
TPoint N(M);
P=f(N);
cout<<"P="<<P.Xcoord()<<","<<P.Ycoord()<<endl;
}
TPoint f(TPoint Q)
{
cout<<"ok\n";
int x,y;
x=Q.Xcoord()+10;
y=Q.Ycoord()+20;
TPoint R(x,y);
return R;
}
执行结果:
Copy_initialization Constructor Called.
Copy_initialization Constructor Called.
ok.
Copy_initialization Constructor Called.
Destructor Called.
Destructor Called.
Destructor Called.
P=30,55
Destructor Called.
Destructor Called.
Destructor Called.
评论