二维平面与三维平面的点(C++继承)

【问题描述】

设计一个类Point_2,表示一个二维平面上的点,具有float型数据成员x和y,保存点的横、纵坐标;设计相应的构造函数对点进行初始化;设计成员函数showPosition()显示点的坐标,getDistance()返回点到(0,0)的距离。

从Point_2公有派生出类Point_3表示三维平面的点,添加数据成员z保存第3维的坐标;设计相应的成员函数。其showPosition()函数显示点的三维坐标,getDistance()函数返回点到(0,0,0)的距离。使用多态来实现。

为两个类设计虚析构函数(函数体可以为空)。

#include  <iostream>
#include  <cmath>
using  namespace  std;

class Point_2 {
public:
    Point_2(float x0, float y0);
    virtual void showPosition();
    virtual float getDistance();
    virtual ~Point_2() = default;
protected:
    float x, y;
};

Point_2::Point_2(float x0, float y0) {
    this->x = x0;
    this->y = y0;
}

void  Point_2::showPosition() {
    cout<<"("<<x<<","<<y<<")"<<endl;
}

float  Point_2::getDistance() {
    float distance = sqrt(x * x + y * y);
    return distance;
}

class Point_3 : public Point_2 {
public:
    Point_3(float x0, float y0, float z0);
    void showPosition();
    float  getDistance();
    virtual ~Point_3() = default;
protected:
    float z;
};

Point_3::Point_3(float x0, float y0, float z0) : Point_2(x0, y0) {
    this->x = x0;
    this->y = y0;
    this->z = z0;
}

void  Point_3::showPosition() {
    cout<<"("<<x<<","<<y<<","<<z<<")"<<endl;
}

float  Point_3::getDistance() {
    float distance = sqrt(x * x + y * y + z * z);
    return distance;
}


int  main() {
    Point_2  *p;
    p=new  Point_2(1.0,1.0);
    p->showPosition();
    cout<<p->getDistance()<<endl;
    delete  p;
    p=new  Point_3(2.0,  5.5,  7.8);
    p->showPosition();
    cout<<p->getDistance()<<endl;
    delete  p;
    return  0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

*OASIS*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值