题目 定义一个Point类,用来产生平面上的点对象。两点决定一条线段,即线段由点构成。因此,Line类使用Point类的对象作为数据成员,然后在Line类的构造函数中求出线段的长度。
要求:
① 定义两个类Point和Line;
② 能够自己输入点的坐标(x, y),有相应的提示语句,如:‘please input xxx’;
③ 可以输出线段的长度
④ 必须基于面向对象的方式实现,不可直接用面向过程的方式实现
定义一个Point类,用来产生平面上的点对象。两点决定一条线段,即线段由点构成。因此,Line类使用Point类的对象作为数据成员,然后在Line类的构造函数中求出线段的长度。
要求:
//① 定义两个类Point和Line;
//② 能够自己输入点的坐标(x, y),有相应的提示语句,如:‘please input xxx’;
//③ 可以输出线段的长度
//④ 必须基于面向对象的方式实现,不可直接用面向过程的方式实现
#include<iostream>
#include<string>
using namespace std;
class point //定义点x,y
{
private:
double x, y;
public:
point(double a, double b);
point(point& p);
double getx();
double gety();
};
class line
{
private:
point a, b; //两点
double length; //线段长度
public:
line(point p1,point p2);
double getlength();
};
point::point(double a, double b)
{
x = a, y = b;
}
point::point(point& p)
{
x = p.x;
y = p.y;
}
double point::getx()
{
return x;
}
double point::gety()
{
return y;
}
line::line(point p1, point p2):a(p1), b(p2)
{
length = sqrt((p1.getx() - p2.getx()) * (p1.getx() - p2.getx()) + (p1.gety() - p2.gety()) * (p1.gety() - p2.gety())); //计算线段的长度
}
double line::getlength()
{
return length;
}
int main()
{
double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
cout << "请输入 x1,y2 和 x2,y2 : ";
cin >> x1 >> y1 >> x2 >> y2;
point a(x1, y1), b(x2, y2);
line line(a, b);
cout << "两点之间的距离:"<<line.getlength() << endl;
return 0;
}