MST
星途 面试题库

面试题:C++中多态实现的必要条件之基础应用

请编写一个C++程序,展示通过虚函数和指针或引用来实现多态。要求至少有一个基类和两个派生类,在基类中有虚函数,在派生类中重写该虚函数,并在主函数中通过基类指针或引用调用虚函数,体现多态特性。并简要说明程序中体现多态实现的必要条件是什么。
45.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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;
}

程序中体现多态实现的必要条件:

  1. 继承:派生类继承基类,如CircleRectangle继承自Shape
  2. 虚函数:在基类中定义虚函数,如Shape类中的draw函数,且在派生类中重写该虚函数。
  3. 通过基类指针或引用调用虚函数:在main函数中,通过Shape*指针指向不同派生类对象,并调用虚函数draw,从而根据指针实际指向的对象类型来决定调用哪个派生类的重写版本。