當一個類中包含其他類的物件時建構函式的呼叫順序
阿新 • • 發佈:2019-01-27
1.按在組合類的定義中出現的順序呼叫內嵌物件的建構函式(與初始化列表中出現的順序無關)
2.呼叫本類建構函式的函式體
組合類建構函式定義的一般形式一般為:
類名::類名(形參表):內嵌物件1(形參表),內嵌物件2(形參表),……
{類的初始化}
#include <iostream>
#include <cmath>
using namespace std;
class point {
public:
point(int xx=0,int yy=0)
{
x=xx;
y=yy;
cout <<"create point"<<endl;
}
point(point &p);
int getx(){return x;}
int gety(){return y;}
private:
int x,y;
};
point::point(point &p){
x=p.x;
y=p.y;
cout<<"copy point "<<endl;
}
class line
{
public:
line(point xp1,point xp2);
line(line &l);
double getlen(){return len;}
private:
point p1,p2;
double len;
};
line::line(point xp1,point xp2):p1(xp1),p2(xp2){
cout<<"create line"<<endl;
double x=double(p1.getx()-p2.getx());
double y=double(p1.gety()-p2.gety());
len=sqrt(x*x+y*y);
}
line::line(line &l):p1(l.p1),p2(l.p2){
cout <<"copy line"<<endl;
len=l.len;
}
int main(int argc, char *argv[])
{
point myp1(1,1),myp2(4,5);
line lin(myp1,myp2);
line lin2(lin);
cout<<"length of lin:"<<lin.getlen()<<endl;
cout<<"length of lin2:"<<lin2.getlen()<<endl;
return 0;
}
結果如下:
create point
create point
copy point
copy point
copy point
copy point
create line
copy point
copy point
copy line
length of lin:5
length of lin2:5
可以看到在創造line的物件前,先呼叫了point類的複製建構函式建立了兩個point類的物件.之後才開始呼叫自己的建構函式.