练习七 多态

题目描述

设计一个Distance基类,其中包括两个点的二维坐标,以及一个用来计算两点之间距离的纯虚函数。 设计两个派生自Distance的类ManhattanDistance和EuclideanDistance,分别计算两点之间的曼哈顿距离和欧几里得距离。

输入

输入4个int类型的数字,范围[0, 40000],分别为第一个点的x、y坐标和第二个点的x、y坐标。

输出

输出两个点之间的曼哈顿距离和欧几里得距离的平方。

样例输入

1 2 3 4

样例输出

4 8

提示

不需要实现循环输入; 要求使用基类指针动态联编的方式调用派生类的函数; 曼哈顿距离的公式为dis=|x1-x2|+|y1-y2|; 欧几里得距离极为常见的两点间距离公式。

#include <iostream>
#include <cmath>

using namespace std;

class Distance   //基类
{
public:
    Distance(int x1 = 0, int y1 = 0, int x2 = 0, int y2 = 0) : x1_(x1), y1_(y1), x2_(x2), y2_(y2) {}

    virtual double CalcDistance() = 0;    //纯虚函数
protected:
    int x1_, y1_, x2_, y2_;    //两个点的坐标
};

class ManhattanDistance : public Distance   //派生类,曼哈顿距离
{
public:
    ManhattanDistance(int x1 = 0, int y1 = 0, int x2 = 0, int y2 = 0) : Distance(x1, y1, x2, y2) {}

    virtual double CalcDistance()    //重载纯虚函数
    {
        return abs(x1_ - x2_) + abs(y1_ - y2_);    //计算曼哈顿距离
    }
};

class EuclideanDistance : public Distance   //派生类,欧几里得距离
{
public:
    EuclideanDistance(int x1 = 0, int y1 = 0, int x2 = 0, int y2 = 0) : Distance(x1, y1, x2, y2) {}

    virtual double CalcDistance()    //重载纯虚函数
    {
        return pow(x2_ - x1_, 2) + pow(y2_ - y1_, 2);    //计算欧几里得距离的平方
    }
};

int main() {
    int x1, y1, x2, y2;
    cin >> x1 >> y1 >> x2 >> y2;

    Distance *p = new ManhattanDistance(x1, y1, x2, y2);    //定义ManhattanDistance类指针
    cout << p->CalcDistance() << " ";
    delete p;

    p = new EuclideanDistance(x1, y1, x2, y2);    //定义EuclideanDistance类指针
    cout << p->CalcDistance() << endl;
    delete p;

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

纳皮尔的骨头

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

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

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

打赏作者

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

抵扣说明:

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

余额充值