关于下面代码,说法错误的是( )。
1 class Shape { 2 protected: 3 string name; 4 5 public: 6 Shape(const string& n) : name(n) {} 7 8 virtual double area() const { 9 return 0.0; 10 } 11 }; 12 13 class Circle : public Shape { 14 private: 15 double radius; // 半径 16 17 public: 18 Circle(const string& n, double r) : Shape(n), radius(r) {} 19 20 double area() const override { 21 return 3.14159 * radius * radius; 22 } 23 }; 24 25 class Rectangle : public Shape { 26 private: 27 double width; // 宽度 28 double height; // 高度 29 30 public: 31 Rectangle(const string& n, double w, double h) : Shape(n), width(w), height(h) {} 32 33 double area() const override { 34 return width * height; 35 } 36 }; 37 38 int main() { 39 Circle circle("MyCircle", 5.0); 40 Rectangle rectangle("MyRectangle", 4.0, 6.0); 41 42 Shape* shapePtr = &circle; 43 cout << "Area: " << shapePtr->area() << endl; 44 45 shapePtr = &rectangle; 46 cout << "Area: " << shapePtr->area() << endl; 47 48 return 0; 49 }
语句Shape*shapePtr=&circle;和shapePtr=&rectangle; 出现编译错误
Shape为基类,Circle和Rectangle是派生类
通过继承,Circle和Rectangle复用了Shape的属性和方法,并扩展了新的功能
Circle和Rectangle通过重写(override)基类的虚函数area和基类指针,实现了运行时多态