导入实习 3 的 Point 类,其定义如下。
#include <iostream>
#include<cmath>
using namespace std;
class Point{
public:
Point( doubl newX=0, double newY=0);
Point(const Point& p);
~Point();
void setValue(double newX, double newY);
double getX( ) const;
double getY() const;
double getDistance( cosnt Point& p2) const;
private:
double x, y;
};
现要定义处理 3 维点的类,而又不能直接修改 Point 类,以 Point 类作为基
类派生得到 Point3D,Point3D 的定义和部分功能已经实现,请补充未完成的部
分成员函数定义。要求构造函数通过初始化列表实现。
class Point3D : public Point{
public:
Point3D(double newX=0, double newY=0, double newZ=0);
double getZ() const;
double getDistance( const Point3D& p)const;
private:
double z;
};
【提示】在 Point3D 的 getDistance 方法中,通过类名前缀可以调用基类的
getDistance,计算出 XY 平面内的距离 dis,再通过 sqrt(disdis+dzdz)即可计算
出 3D 空间内点的距离。
测试的主程序如下:
int main(){
Point p1(3, 4), p2(5,3);
Point3D p1_3D(3,4,6);
Point3D p2_3D(2,6,9);
double dis=p1.getDistance(p2); //计算二维点 p1 和 p2 的距离
cout<<"Distance between p1 and p2: "<<dis<<endl;
dis=p1_3D.getDistance(p2_3D); //计算 3 维点 p1_3D 和 p2_3D 的距离
cout<<"Distance between p1_3D and p2_3D: "<<dis<<endl;
return 0;
}