多态继承的一个小例子,mark一下。

来源:互联网 发布:淘宝宝贝卖点怎么写 编辑:程序博客网 时间:2024/05/22 04:45
#include <iostream>using namespace std;class Point2d{public:Point2d( float x = 0.0, float y = 0.0) : _x(x),_y(y){};float x(){ return _x; }float y(){ return _y; }virtual float z(){ return 0.0;}virtual void z(float){ }virtual void operator+=(Point2d& rhs){_x += rhs.x();_y += rhs.y();}protected:float _x, _y;};class Point3d : public Point2d{public:Point3d(float x = 0.0, float y = 0.0, float z = 0.0) : Point2d(x, y), _z(z){};float z(){ return _z;}void z(float newZ){ _z=newZ; }void operator+=(Point2d& rhs){Point2d::operator+=(rhs);_z += rhs.z();}protected:float _z;};int main(){Point2d p2d(2.1, 2.2);Point3d p3d(3.1, 3.2, 3.3);p3d += p2d;cout<<"p3d data members: "<<p3d.x()<<" "<<p3d.y()<<" "<<p3d.z()<<endl;}