面试题答案
一键面试多态的概念
在C++ 中,多态是指一个接口多种实现,即通过基类指针或引用调用虚函数时,会根据指针或引用所指向对象的实际类型来决定调用哪个类的虚函数版本。它允许我们使用基类的指针或引用对派生类的对象进行操作,使得代码能够根据对象的实际类型来调用适当的函数,提高了代码的灵活性和可扩展性。
实际编程场景 - 图形绘制程序
#include <iostream>
#include <cmath>
// 基类Shape
class Shape {
public:
// 虚函数draw,用于绘制图形
virtual void draw() const {
std::cout << "绘制一个形状" << std::endl;
}
};
// 圆形类,继承自Shape
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
// 重写draw函数,绘制圆形
void draw() const override {
std::cout << "绘制一个半径为 " << radius << " 的圆形" << std::endl;
}
};
// 矩形类,继承自Shape
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
// 重写draw函数,绘制矩形
void draw() const override {
std::cout << "绘制一个宽为 " << width << ",高为 " << height << " 的矩形" << std::endl;
}
};
在主函数中利用多态实现对不同形状的统一绘制操作:
int main() {
// 创建Shape指针数组
Shape* shapes[2];
shapes[0] = new Circle(5.0);
shapes[1] = new Rectangle(4.0, 3.0);
// 遍历数组,通过基类指针调用draw函数,实现多态
for (int i = 0; i < 2; ++i) {
shapes[i]->draw();
delete shapes[i];
}
return 0;
}
在上述代码中,Shape
类定义了一个虚函数 draw
。Circle
和 Rectangle
类继承自 Shape
类,并各自重写了 draw
函数。在 main
函数中,通过 Shape
类型的指针数组存储不同形状的对象指针,然后通过遍历该数组,调用 draw
函数,此时会根据指针实际指向的对象类型(Circle
或 Rectangle
)来调用相应的 draw
函数版本,从而实现多态的统一绘制操作。