MST

星途 面试题库

面试题:C++中继承的优势在代码复用方面如何体现

请举例说明在C++中,通过继承如何实现代码复用。例如,设计一个简单的类继承体系,展示基类的成员函数和数据成员如何被派生类复用,同时阐述这种复用相较于直接复制粘贴代码有哪些优点。
12.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

1. 类继承体系示例

#include <iostream>

// 基类
class Shape {
protected:
    int x;
    int y;
public:
    Shape(int a, int b) : x(a), y(b) {}

    void move(int newX, int newY) {
        x = newX;
        y = newY;
    }

    virtual void draw() const {
        std::cout << "Drawing a shape at (" << x << ", " << y << ")" << std::endl;
    }
};

// 派生类
class Rectangle : public Shape {
private:
    int width;
    int height;
public:
    Rectangle(int a, int b, int w, int h) : Shape(a, b), width(w), height(h) {}

    void draw() const override {
        std::cout << "Drawing a rectangle at (" << x << ", " << y << ") with width " << width << " and height " << height << std::endl;
    }
};

2. 代码复用说明

  • 数据成员复用Rectangle 类继承自 Shape 类,Rectangle 类可以复用 Shape 类的 xy 数据成员,通过 Shape(a, b) 调用 Shape 类的构造函数初始化 xy
  • 成员函数复用Rectangle 类复用了 Shape 类的 move 函数,这样 Rectangle 对象也具备移动功能。同时 Rectangle 类重写了 draw 函数,以实现自己特定的绘制逻辑,但仍然基于 Shape 类提供的位置信息。

3. 相较于直接复制粘贴代码的优点

  • 维护性增强:如果 Shape 类的 move 函数需要修改(例如添加日志记录),只需要在 Shape 类中修改一次,所有继承自 Shape 的派生类(如 Rectangle)都会自动应用这些修改。而如果是复制粘贴代码,每个副本都需要单独修改,容易出错。
  • 代码精简:避免了大量重复代码。例如在上述例子中,如果不使用继承复用,Rectangle 类需要自己重新实现 xy 数据成员以及 move 函数,代码量会显著增加。
  • 扩展性好:可以方便地在基类中添加新的功能,所有派生类都能自然地继承这些新功能。比如在 Shape 类中添加一个 scale 函数,所有派生类(如 Rectangle)都自动具备了缩放功能。