2020-08-30

初学者必看!!!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的拷贝构造函数

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温JZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值