C++ public、protected、private 继承方式的区别

时间:2021-03-01 09:26:00

访问修饰符 public、protected、private,无论是修饰类内成员(变量、函数),还是修饰继承方式,本质上实现的都是可见性的控制。

Difference between private, public, and protected inheritance

class A  {
public: int x;
protected: int y;
private: int z;
};

class B : public A {
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D
};
  • 需要说明的是,类 B、C、D 的内存结构中均包含 x, y, z (继承而来的成员),只是访问权限的不同罢了;
  • protected 修饰类内的成员,表示该成员仅对该类及其派生类可见;
  • private 继承(class D : private A )使得所有成员都变为 private(父类中的 private 成员对子类不可见,哪怕是 public 继承),其子类均可不见,也即再有新的派生类继承 class D,成员函数的重写就失去了意义;