关于下面 Shape/Circle/Rectangle 多态代码,说法错误的是:
class Shape { protected: string name;
public:
Shape(const string& n) : name(n) {}
virtual double area() const { return 0.0; }
};
class Circle : public Shape { double radius;
public:
Circle(const string& n, double r) : Shape(n), radius(r) {}
double area() const override { return 3.14159*radius*radius; }
};
class Rectangle : public Shape { double width, height;
public:
Rectangle(const string& n, double w, double h) : Shape(n), width(w), height(h) {}
double area() const override { return width*height; }
};
int main() {
Circle circle("MyCircle", 5.0);
Rectangle rectangle("MyRectangle", 4.0, 6.0);
Shape* shapePtr = &circle; cout << shapePtr->area() << endl;
shapePtr = &rectangle; cout << shapePtr->area() << endl;
}
- A. 语句 Shape* shapePtr = &circle; 和 shapePtr = &rectangle; 会出现编译错误。
- B. Shape 为基类,Circle 和 Rectangle 是派生类。
- C. Circle 和 Rectangle 通过继承复用了 Shape 的属性和方法,并扩展了新功能。
- D. Circle、Rectangle 通过重写虚函数 area 和基类指针实现了运行时多态。
正确答案:A