继承与多态 相关问题 求解!

导入实习 3 的 Point 类,其定义如下。

#include 
#include
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: "<"Distance between p1_3D and p2_3D: "<
return 0;
}

下面是 Point3D 类的成员函数定义:

class Point3D : public Point {
public:
    Point3D(double newX = 0, double newY = 0, double newZ = 0) : Point(newX, newY), z(newZ) {}
    double getZ() const { return z; }
    double getDistance(const Point3D& p) const {
        double dis2D = Point::getDistance(p);
        double dis3D = sqrt(dis2D * dis2D + pow(z - p.z, 2));
        return dis3D;
    }
private:
    double z;
};

在构造函数中使用了初始化列表来初始化基类的 x 和 y 成员变量,同时初始化自身的 z 成员变量。

在 getDistance 方法中,首先调用基类 Point 的 getDistance 方法,计算出 2D 平面内的距离 dis2D,然后再利用勾股定理计算出 3D 空间内的距离 dis3D,最终返回 dis3D。

在主程序中可以直接调用 Point 和 Point3D 的 getDistance 方法,计算出两个点之间的距离。完整的程序代码如下:

#include <iostream>
#include <cmath>

using namespace std;

class Point {
public:
    Point(double newX = 0, double newY = 0) : x(newX), y(newY) {}
    Point(const Point& p) : x(p.x), y(p.y) {}
    ~Point() {}
    void setValue(double newX, double newY) { x = newX; y = newY; }
    double getX() const { return x; }
    double getY() const { return y; }
    double getDistance(const Point& p2) const {
        double dx = x - p2.x;
        double dy = y - p2.y;
        return sqrt(dx * dx + dy * dy);
    }
private:
    double x, y;
};

class Point3D : public Point {
public:
    Point3D(double newX = 0, double newY = 0, double newZ = 0) : Point(newX, newY), z(newZ) {}
    double getZ() const { return z; }
    double getDistance(const Point3D& p) const {
        double dis2D = Point::getDistance(p);
        double dis3D = sqrt(dis2D * dis2D + pow(z - p.z, 2));
        return dis3D;
    }
private:
    double z;
};

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);
    cout << "Distance between p1 and p2: " << dis << endl;
    dis = p1_3D.getDistance(p2_3D);
    cout << "Distance between p1_3D and p2_3D: " << dis << endl;
    return 0;
}