面试题答案
一键面试定义抽象类示例代码
#include <iostream>
// 定义抽象类
class Shape {
public:
// 纯虚函数,使得该类成为抽象类
virtual double calculateArea() const = 0;
virtual void display() const = 0;
};
// 圆形类继承自抽象类Shape
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double calculateArea() const override {
return 3.14159 * radius * radius;
}
void display() const override {
std::cout << "Circle with radius " << radius << ", area: " << calculateArea() << std::endl;
}
};
// 矩形类继承自抽象类Shape
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double calculateArea() const override {
return width * height;
}
void display() const override {
std::cout << "Rectangle with width " << width << " and height " << height << ", area: " << calculateArea() << std::endl;
}
};
适用场景
- 图形绘制与计算:在一个图形绘制和计算面积的程序中,我们可以定义
Shape
抽象类,然后让Circle
、Rectangle
等具体图形类继承自Shape
。这样,我们可以通过Shape
指针或引用的方式来处理不同类型的图形,使得代码更具扩展性和可维护性。例如:
int main() {
Shape* shapes[2];
shapes[0] = new Circle(5);
shapes[1] = new Rectangle(4, 6);
for (int i = 0; i < 2; ++i) {
shapes[i]->display();
delete shapes[i];
}
return 0;
}
在上述代码中,main
函数通过Shape
指针数组来管理不同类型的图形对象,调用display
函数时会根据实际对象的类型进行动态绑定,执行相应的函数实现。如果后续需要添加新的图形类型,只需要定义新的类继承自Shape
并实现其纯虚函数即可,而不需要修改大量现有代码。