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类的对象.之后才开始调用自己的构造函数.