题目描述
设计一个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;
}