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
类的 x
和 y
数据成员,通过 Shape(a, b)
调用 Shape
类的构造函数初始化 x
和 y
。
- 成员函数复用:
Rectangle
类复用了 Shape
类的 move
函数,这样 Rectangle
对象也具备移动功能。同时 Rectangle
类重写了 draw
函数,以实现自己特定的绘制逻辑,但仍然基于 Shape
类提供的位置信息。
3. 相较于直接复制粘贴代码的优点
- 维护性增强:如果
Shape
类的 move
函数需要修改(例如添加日志记录),只需要在 Shape
类中修改一次,所有继承自 Shape
的派生类(如 Rectangle
)都会自动应用这些修改。而如果是复制粘贴代码,每个副本都需要单独修改,容易出错。
- 代码精简:避免了大量重复代码。例如在上述例子中,如果不使用继承复用,
Rectangle
类需要自己重新实现 x
、y
数据成员以及 move
函数,代码量会显著增加。
- 扩展性好:可以方便地在基类中添加新的功能,所有派生类都能自然地继承这些新功能。比如在
Shape
类中添加一个 scale
函数,所有派生类(如 Rectangle
)都自动具备了缩放功能。