C++:编写一个点类Point,再由它派生线段类Line。

来源:百度知道 编辑:UC知道 时间:2024/06/17 14:42:07
要求:Point只能有一个构造函数,而且构造函数只能有两个参数(点的x,y坐标)。并将下面不完整的测试主程序补充完整,以便对你定义的点类及线段类进行测试。
void main()
{
Point a;
Point b(7.8,9.8),c(34.5,67,8);
a=c;
cout<<”两点之间距离是:”<<a.Distance(b)<<endl;
Line s(7.8,8.34,34.5,67.8);
cout<<s.Display()<<endl;
}

#include<iostream>
#include<cmath>

using namespace std;

class Point
{
private:
float x,y;
public:
Point(){}
Point(float a,float b):x(a),y(b){}
Point(Point& a);
float Distance(Point b);
};

Point::Point(Point& a)
{
x=a.x;
y=a.y;
}

float Point::Distance(Point b)
{
return sqrt((x-b.x)*(x-b.x)+(y-b.y)*(y-b.y));
}

class Line:public Point
{
private:
Point a,b;
public:
Line(float x1,float y1,float x2,float y2):a(x1,y1),b(x2,y2){}
float Display();
};

float Line::Display()//这个地方不知道你要输出的是什么,但从你的源程序中知道要返回一个值,所以,我返回了线段的距离
{
return a.Distance(b);
}
int main()
{
Point a;
Point b(7.8,9.8),c(34.5,67.8);
a=c;
cout<<"两点之间距离是:"<<a.Distance(b)<<endl;
Line s(7.8,8.34,34.5,67.8);
cout<<s.Display()&