C++ 继承

创建于 2024-12-03 / 30
字体: [默认] [大] [更大]

继承

在 C++ 中,可以从一个类继承到另一个类的属性和方法。我们将继承概念分为两类:

  • 派生类(子类)derived class (child) - 从另一个类继承的类
  • 基类(父级)base class (parent) - 从中继承的类

要从类继承,请使用:符号。

在下面的示例中,Car类(child)从Vehicle类(parent)继承属性和方法:

实例

// 基类
class Vehicle {
  public:
    string brand = "Ford";
    void honk() {
      cout << "Tuut, tuut! \n" ;
    }
};

// 派生类
class Car: public Vehicle {
  public:
    string model = "Mustang";
};

int main() {
  Car myCar;
  myCar.honk();
  cout << myCar.brand + " " + myCar.model;
  return 0;
} 运行实例 »

为什么要使用继承?

因为它对代码的可重用性很有用:在创建新类时重用现有类的属性和方法。




0 人点赞过