第三节 · 进化论 · 虚函数与抽象基类
class Shape
{
public:
// 虚函数:允许派生类重写
virtual void draw() const
{
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape
{
public:
void draw() const override // override 确保是重写
{
cout << "Drawing a circle" << endl;
}
};
class Rectangle : public Shape
{
public:
void draw() const override
{
cout << "Drawing a rectangle" << endl;
}
};
int main()
{
Shape* shapes[3];
shapes[0] = new Shape();
shapes[1] = new Circle();
shapes[2] = new Rectangle();
for (int i = 0; i < 3; ++i)
{
shapes[i]->draw(); // 根据实际类型调用
}
// 清理
for (int i = 0; i < 3; ++i)
delete shapes[i];
return 0;
}
// 输出:
// Drawing a shape
// Drawing a circle
// Drawing a rectangle习题
Last updated