代码实现
#include <iostream>
class Shape {
protected:
virtual void draw() const {
std::cout << "This is a Shape." << std::endl;
}
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "This is a Circle." << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() const override {
std::cout << "This is a Rectangle." << std::endl;
}
};
void display(Shape* s) {
if (s) {
s->draw();
}
}
合理性
- 多态性体现:通过将
draw
函数定义为虚函数,使得display
函数能够根据传入对象的实际类型(Circle
或Rectangle
)来调用相应的draw
函数,实现了运行时的多态性,提高了代码的灵活性和可扩展性。当有新的派生类(如Triangle
)继承Shape
类时,只需要在新类中重写draw
函数,display
函数无需修改即可支持新类型。
- 代码复用:
display
函数的实现不依赖于具体的派生类类型,只依赖于基类指针,使得代码可以复用。
可能存在的风险
- 空指针风险:在
display
函数中,如果传入的指针s
为空,调用draw
函数会导致程序崩溃。虽然在display
函数中进行了简单的空指针检查,但在调用display
函数之前仍有可能出现未检查空指针的情况。
- 访问权限变化:基类中
draw
函数是保护成员,派生类将其访问权限改为公有,这可能会破坏基类封装的原则。在某些情况下,这种访问权限的变化可能会导致不符合预期的行为,因为原本在基类设计中,draw
函数是不想被外部直接调用的,而派生类的改变使得外部可以调用。