C++ private, public 和 protected 继承的区别

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
};
  • public继承不改变基类成员的访问权限;
  • private继承使得基类所有成员在子类中的访问权限变为private;
  • protected继承将基类中public成员变为子类的protected成员,其它成员的访问权限不变;
  • 基类中的private成员不受继承方式的影响,子类永远无权访问;

IMPORTANT NOTE: Classes B, C and D all contain the variables x, y and z. It is just question of access.

About usage of protected and private inheritance you could read here.

posted @ 2022-04-01 15:56  卡尔的思索  阅读(63)  评论(0编辑  收藏  举报