补充代码:
#include<iostream> using namespace std; class Shape//形状类 { public: virtual double calcArea() { cout << "calcArea" << endl; return 0; } }; class Circle:public Shape //公有继承自形状类的圆形类 { public: Circle(double r) :m_dR(r){} double calcArea(); private: double m_dR; }; double Circle::calcArea() { return 3.14*m_dR*m_dR; } class Rect :public Shape //公有继承自形状类的矩形类 { public: Rect(double width, double height) :m_dHeight(width), m_dWidth(height){} double calcArea(); private: double m_dWidth; double m_dHeight; }; double Rect::calcArea() { return m_dWidth*m_dHeight; } int main() { /*基类指针指向派生类对象的方式*/ Shape *shape1 = new Circle(4.0); Shape *shape2 = new Rect(3.0, 5.0); cout<<"area="<<shape1->calcArea(); cout<<"area="<<shape2->calcArea(); /*基类对象引用绑定到派生类对象上的方式*/ /*Rect rct(3.0, 5.0); Shape &r = rct; cout << "area=" << r.calcArea();*/ system("pause"); return 0; }