2、继承与派生:同名成员屏蔽与类型兼容规则
(a) 设计一个Point 的类,表示平面坐标下的一个点,这个类包括:
两个私有型double数据成员:x, y,分别表示横坐标和纵坐标
一个不带形参的构造函数:Point(),用于创建原点(0,0)
一个带形参的构造函数:Point(double x, double y)
成员函数doubledist(const Point& p),返回当前点(目标对象)与给定点(形参)的距离
(b) 设计一个Point3D 类,表示三维空间的一个点,以公有方式继承Point,这个类包括:
一个私有型double数据成员:z,表示z-坐标
一个不带形参的构造函数:Point3D(),用于创建原点(0,0,0)
一个带形参的构造函数:Point3D(double x, double y, double z)
成员函数doubledist(const Point3D& p),返回当前点与给定点的距离
实现这两个类,并在主函数中测试:
(1) 创建点A1(0,0) 和A2(4,5.6),并输出它们之间的距离。
(2) 创建点B1(0,0,0) 和B2(4,5.6,7.8),并输出它们之间的距离。
(程序取名为hw13_02.cpp)
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
public:
Point() {
x=0;y=0;
}
Point(double x, double y) {
this->x=x; this->y=y;
}
double dist(const Point& p) const {
return pow(pow(x-p.x,2)+pow(y-p.y,2),0.5);
}
protected:
double x,y;
};
class Point3D : public Point
{
public:
Point3D() {z=0;}
Point3D(double x, double y, double z) : Point(x,y) {this->z=z;}
double dist(const Point3D& p) const {
return pow(pow(Point::dist(p),2)+pow(z-p.z,2),0.5);
}
private:
double z;
};
int main()
{
Point A1, A2(4,5.6);
Point3D B1, B2(4,5.6,7.8);
cout << "|A1-A2|=" << A1.dist(A2) << endl;
cout << "|B1-B2|=" << B1.dist(B2) << endl;
return 0;
}
Post Views: 5