【问题描述】
设计一个类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;
}