面试题答案
一键面试#include <iostream>
// 基类
class Shape {
public:
// 虚函数
virtual void draw() const {
std::cout << "Drawing a shape." << std::endl;
}
};
// 派生类1
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a circle." << std::endl;
}
};
// 派生类2
class Rectangle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a rectangle." << std::endl;
}
};
int main() {
Shape* shapePtr;
Circle circle;
Rectangle rectangle;
// 通过基类指针指向Circle对象并调用draw函数
shapePtr = &circle;
shapePtr->draw();
// 通过基类指针指向Rectangle对象并调用draw函数
shapePtr = &rectangle;
shapePtr->draw();
return 0;
}
程序中体现多态实现的必要条件:
- 继承:派生类继承基类,如
Circle
和Rectangle
继承自Shape
。 - 虚函数:在基类中定义虚函数,如
Shape
类中的draw
函数,且在派生类中重写该虚函数。 - 通过基类指针或引用调用虚函数:在
main
函数中,通过Shape*
指针指向不同派生类对象,并调用虚函数draw
,从而根据指针实际指向的对象类型来决定调用哪个派生类的重写版本。