Number:10
Title:FORTRAN Author:Wang Number:20
构造函数还有一种称为“初始式”的形式对数据成员置初值。形式为:
构造函数名(参数表):数据成员1(参数),
数据成员2(参数),?
{ ?? } 例如:
TDate3::TDate3(int y,int m,int d) { year=y; month=m; day=d;
cout<<”:Constructor called.\\n”;} 可以:
TDate3::TDate3(int y,int m,int d): year(y),month(m),day(d)
{cout<<”:Constructor called.\\n”;}
例5.8 对象成员初始化 #include
{ public:
A(int x):a(x){ } int a; };
class B { public:
B(int x,int y):aa(x),b(y) { } void out( )
{cout<<”aa=”<
void main( ) { B objB(3,5); objB.out( ); } 输出:
aa=3 b=5
b=”
以上不能:
B(int x,int y)
{ aa.a=x; b=y; } 不能在构造函数中对类成员赋值 但可以:
B(int x,int y):aa(x) { b=y; }
5.3.3 拷贝初始化构造函数
功能:
是用一个已知的对象来初始化一个被创建的同类的对象。
格式:
类名::拷贝初始化构造函数名(const 类名 &引用名)
特点:
1.也是一种构造函数,函数名同类名。
2.只有一个参数,并且是对某个对象的引用。 3.如果类中没有说明拷贝初始化构造函数,则系统自动生成一个缺省拷贝初始化构造函数。
例5.9 修改点类的定义。
//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
{ TPoint P1(5,7);
TPoint P2(P1);
cout<<”P2=”< < Copy_initialization Constructor Called. P2=5,7 Destructor Called. Destructor Called. 例5.10 拷贝初始化构造函数的其他用法。 #include { TPoint M(20,35),P(0,0); TPoint N(M); P=f(N); cout<<”P=”< <