程序代码
#include <iostream>
#include <Cmath>
using namespace std;
class Point //定义坐标点类
{
public:
Point(double x = 0, double y = 0);//构造函数
double getX();//得到x坐标
double getY();//得到y坐标
void PrintPoint(); //输出点的信息
private:
double x,y;//点的横坐标和纵坐标
};
//构造函数
Point::Point(double x, double y)
{
this->x = x;
this->y = y;
}
//得到点的x坐标
double Point::getX()
{
return x;
}
//得到点的y坐标
double Point::getY()
{
return y;
}
void Point::PrintPoint()//输出点的信息
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
class Line: public Point //利用坐标点类定义直线类, 其基类的数据成员表示直线的中点
{
public:
Line(Point pts, Point pte);//构造函数,用初始化直线的两个端点及由基类数据成员描述的中点
double getLength();//计算直线的长度
void PrintLine();//输出直线的两个端点和直线长度
private:
class Point pts, pte;//直线的两个端点
};
//构造函数,分别用初始化直线的两个端点及由基类数据成员(属性)描述的中点
Line::Line(Point pt1, Point pt2):Point((pt1.getX()+pt2.getX())/2,(pt1.getY()+pt2.getY())/2)
{
pts = pt1;
pte = pt2;
}
double Line::getLength()//计算直线的长度
{
double d;//保存直线的长度
d = sqrt((pts.getX() - pte.getX())*(pts.getX() - pte.getX()) +
(pts.getY() - pte.getY())*(pts.getY() - pte.getY()));
return d;
}
void Line::PrintLine()//输出直线的两个端点和直线长度
{
cout<<"直线的长度:"<<getLength()<<endl;
}
void main()
{
//定义两个点的对象
Point ps(0,0), pe(3,4);
//定义一个直线对象
Line l(ps,pe);
//输出两个点的坐标
cout<<"ps:";
ps.PrintPoint();
cout<<"pe:";
pe.PrintPoint();
//输出直线的长度
l.PrintLine();
//输出中点的坐标
cout<<"直线l的中点的坐标:";
l.PrintPoint();
system("pause");
}
执行结果: