MST

星途 面试题库

面试题:C++ 类的继承与多态性在类定义中的体现

设计一个类层次结构,基类为 `Shape`,包含纯虚函数 `calculateArea`。派生出 `Rectangle` 和 `Triangle` 类,在这两个派生类中实现 `calculateArea` 函数来计算各自的面积。并解释在这个过程中,C++ 如何通过虚函数和指针或引用来实现多态性。请给出完整的类定义和测试代码,以展示多态性的工作原理。
23.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

// 基类 Shape
class Shape {
public:
    // 纯虚函数 calculateArea
    virtual double calculateArea() const = 0;
};

// 派生类 Rectangle
class Rectangle : public Shape {
private:
    double width;
    double height;

public:
    Rectangle(double w, double h) : width(w), height(h) {}

    // 实现 calculateArea 函数
    double calculateArea() const override {
        return width * height;
    }
};

// 派生类 Triangle
class Triangle : public Shape {
private:
    double base;
    double height;

public:
    Triangle(double b, double h) : base(b), height(h) {}

    // 实现 calculateArea 函数
    double calculateArea() const override {
        return 0.5 * base * height;
    }
};

// 测试多态性的函数
void testPolymorphism(const Shape& shape) {
    std::cout << "The area of the shape is: " << shape.calculateArea() << std::endl;
}

int main() {
    Rectangle rect(5.0, 3.0);
    Triangle tri(4.0, 6.0);

    // 通过引用调用 testPolymorphism 函数展示多态性
    testPolymorphism(rect);
    testPolymorphism(tri);

    // 通过指针调用 testPolymorphism 函数展示多态性
    Shape* rectPtr = &rect;
    Shape* triPtr = &tri;
    std::cout << "The area of the rectangle (using pointer) is: " << rectPtr->calculateArea() << std::endl;
    std::cout << "The area of the triangle (using pointer) is: " << triPtr->calculateArea() << std::endl;

    return 0;
}

在这个过程中,C++ 通过虚函数和指针或引用来实现多态性:

  1. 虚函数:在基类 Shape 中定义了纯虚函数 calculateArea,这意味着任何从 Shape 派生的类都必须实现这个函数。通过将函数声明为 virtual,C++ 启用了动态绑定机制。
  2. 指针或引用:在 testPolymorphism 函数中,参数是 const Shape&,这意味着可以传入 Shape 派生类的对象。当通过这个引用调用 calculateArea 函数时,实际调用的是派生类中重写的 calculateArea 函数,而不是基类的函数。同样,当使用 Shape* 指针时,根据指针实际指向的对象类型(RectangleTriangle),调用相应派生类的 calculateArea 函数。这种根据对象实际类型而非指针或引用类型来决定调用哪个函数的机制就是多态性。