面试题答案
一键面试#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 = ▭
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++ 通过虚函数和指针或引用来实现多态性:
- 虚函数:在基类
Shape
中定义了纯虚函数calculateArea
,这意味着任何从Shape
派生的类都必须实现这个函数。通过将函数声明为virtual
,C++ 启用了动态绑定机制。 - 指针或引用:在
testPolymorphism
函数中,参数是const Shape&
,这意味着可以传入Shape
派生类的对象。当通过这个引用调用calculateArea
函数时,实际调用的是派生类中重写的calculateArea
函数,而不是基类的函数。同样,当使用Shape*
指针时,根据指针实际指向的对象类型(Rectangle
或Triangle
),调用相应派生类的calculateArea
函数。这种根据对象实际类型而非指针或引用类型来决定调用哪个函数的机制就是多态性。