初学者必看!!!C++类组合构造函数析构函数执行顺序问题
class Point
{
public:
Point(int xx=0, int yy=0);
Point(Point &p);
inline int getX();
inline int getY();
private:
int x,y;
};
Point::Point(int xx, int yy)
{
x=xx;
y=yy;
cout<<"Calling the constructor of Point."<<endl;
}
Point::Point(Point &p)
{
x=p.x;
y=p.y;
cout<<"Calling the copy constructor of Point"<<endl;
}
int Point::getX(){ return x; }
int Point::getY(){ return y; }
class Line
{
public:
Line(Point xp1, Point xp2);
Line(Line &line);
inline double getLen();
private:
Point p1,p2;
double len;
};
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2)
{
cout<<"Calling constructor of Line"<<endl;
double x=static_cast<double>(p1.getX()-p2.getX());
double y=static_cast<double>(p1.getY()-p2.getY());
len=sqrt(x*x+y*y);
};
Line::Line(Line &line):p1(line.p1),p2(line.p2)
{
cout<<"Calling the copy constructor of Line"<<endl;
len=line.len;
}
double Line::getLen(){ return len; }
int main()
{
Point myp1(1,1),myp2(4,5);
Line line(myp1,myp2);
Line line2(line);
return 0;
}
Calling the constructor of Point. //
Calling the constructor of Point.//构造对象myp1,myp2
Calling the copy constructor of Point//myp1传递给point xp1调用拷贝构造函数
Calling the copy constructor of Point//myp2传递给point xp2调用拷贝构造函数
Calling the copy constructor of Point//用xp1拷贝构造p1
Calling the copy constructor of Point//用xp2拷贝构造p2
Calling constructor of Line//最后执行函数体中line的构造函数
Calling the copy constructor of Point//用line.xp1拷贝构造p1
Calling the copy constructor of Point//用line.xp2拷贝构造p2
Calling the copy constructor of Line//最后调用函数体中的line的拷贝构造函数