在 C++ 中,类的继承方式有三种:公有继承(public inheritance)、保护继承(protected inheritance)和私有继承(private inheritance)。这些继承方式决定了派生类对基类成员的访问权限。
1. 公有继承(public inheritance):
- 基类的
public
成员在派生类中保持为public
。 - 基类的
protected
成员在派生类中保持为protected
。 - 基类的
private
成员在派生类中不可访问。
class Derived : public Base {// 继承自 Base 的成员在 Derived 中具有 public 访问权限
};
2. 保护继承(protected inheritance):
- 基类的
public
和protected
成员在派生类中变为protected
。 - 基类的
private
成员在派生类中不可访问。
class Derived : protected Base {// 继承自 Base 的成员在 Derived 中具有 protected 访问权限
};
3. 私有继承(private inheritance):
- 基类的
public
和protected
成员在派生类中变为private
。 - 基类的
private
成员在派生类中不可访问。
class Derived : private Base {// 继承自 Base 的成员在 Derived 中具有 private 访问权限
};