两点的距离(类的组合成员、冒号语法)C++

【问题描述】

定义一个坐标点类Point和求两点距离的距离类Distance,在每个类的构造函数函数体里加上cout输出相应的提示语句,以便观察构造函数被调用的顺序。

【注意】请勿修改类的设计和主函数,只需要在类体外补充各个成员函数的具体实现

类的设计和主函数如下:

class Point

{

public:

Point(int xx,int yy);

Point(Point &r);

int GetX();

int GetY();

~Point();

private:

int x,y;

};

class Distance

{

private:

Point p1,p2;

double dist;

public:

Distance(Point a,Point b);

double GetDis();

~Distance();

};

int main()

{

Point myp1(1,1),myp2(4,5);

Distance myd(myp1,myp2);

cout<<endl;

cout<<“the distance is:”<<myd.GetDis()<<endl;

return 0;

}

【样例输入】无输入
【样例输出】

Point’s constructor was called

Point’s constructor was called

Point’s copyConstructor was called

Point’s copyConstructor was called

Point’s copyConstructor was called

Point’s copyConstructor was called

Distance’s constructor was called

Point’s destructor was called

Point’s destructor was called

the distance is:5

Distance’s destructor was called

Point’s destructor was called

Point’s destructor was called

Point’s destructor was called

Point’s destructor was called

#include<iostream>
#include<cmath>

using namespace std;

// 介于格式问题,额外在cout<<"Distance's constructor was called"<<endl<<endl;,以及main函数中cout<<endl;
class Point
{
public:
  Point(int xx,int yy)
  {
   x = xx;y =yy;
   cout<<"Point's constructor was called"<<endl;
  }
  Point(Point &r)
  {
      x=r.x;
      y=r.y;
      cout<<"Point's copyConstructor was called"<<endl;
  }
  int GetX(){return x;}
  int GetY(){return y;}
  ~Point()
  {
      cout<<"Point's destructor was called"<<endl;
  }
private:
  int x,y;
};

class Distance
{
private:
  Point p1,p2;
  double dist;
public:
  Distance(Point a,Point b):p1(a),p2(b)
  {
      cout<<"Distance's constructor was called"<<endl<<endl;
  }
  double GetDis()
  {
      return sqrt(pow(fabs(p1.GetX()-p2.GetX()),2)+pow(fabs(p1.GetY()-p2.GetY()),2));
  }
  ~Distance()
  {
      cout<<"Distance's destructor was called"<<endl;
  }
};

int main()
{
  Point myp1(1,1),myp2(4,5);
  Distance myd(myp1,myp2);
  cout<<endl;
  cout<<"the distance is:"<<myd.GetDis()<<endl;
  cout<<endl;
  return 0;
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值