题:
创建一个二维空间的MyPoint类。 MyPoint类具有x和y分别代表xy坐标,两个x和y的get函数,以及用于返回两个点之间的距离的函数。创建一个三维空间名为ThreeDPoint的类。让ThreeDPoint从MyPoint派生并能够获取Z坐标值,设置一个坐标为(0,0,0)的无参构造函数点和具有三个指定坐标的点的构造函数。设计以(const ThreeDPoint&)形式的函数求距离,编写测试程序求两个点的距离。
通过继承从基类中派生获取基类的函数等,在派生类中可以设计属于自己的函数可来区别于父类,达到自己的特色。
#include<iostream>
#include<cmath>
using namespace std;
class MyPoint
{
public:
double x;
double y;
MyPoint()
{
x = 0;
y = 0;
}//无参构造函数
MyPoint(double x, double y)
{
this->x = x;
this->y = y;
}//设置xy特定值
double getX()
{
return x;
}//返回X
double getY()
{
return y;
}
double getDistance(MyPoint a, MyPoint b)
{
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}//计算2维的两个点距离
};
class ThreeDPoint:public MyPoint
{
public:
double z;
ThreeDPoint()
{
x = 0;
y = 0;
z = 0;
}//无参构造函数使xyz=0
ThreeDPoint(double x, double y, double z)
{
this->x = x;
this->y = y;
this->z = z;
}//给xyz特定值
double getZ() const
{
return z;
}//获取Z的值,只读函数不改变变量的值
double getDistance(const ThreeDPoint& a) const
{
return sqrt((a.x - x) * (a.x - x) + (a.y - y) * (a.y - y) + (a.z - z) * (a.z - z));
}//获取三维空间两点的距离
};
int main()
{
ThreeDPoint point1(0,0,0);
ThreeDPoint point2(10, 30, 25.5);
double diatance = point2.getDistance(point1);
cout << "The distance between them is: " << point2.getDistance(point1) << endl;
return 0;
}