参考:
C++中的private, public, protected_c++ private-CSDN博客
https://www.cnblogs.com/corineru/p/11001242.html
C++ 中 Private、Public 和 Protected 的区别
Private | Public | Protected |
声明为private类成员只能由基类内部的函数访问。 | 可以从任何地方访问声明为public的类成员。 | 声明为protected类成员可以在基类及其派生类中访问。 |
private成员使用关键字private后跟冒号 (:) 字符来声明。 | public成员使用关键字public后跟冒号 (:) 字符来声明。 | protected成员使用关键字protected后跟冒号 (:) 字符来声明。 |
private成员能被子类继承,但不能被子类的对象直接访问。 | public成员可以在子类中被继承并被直接访问。 | protected成员可以在子类中被继承并访问。 |
它为其数据成员提供高安全性。 | 它不为其数据提供任何类型的安全性。 | 它提供的安全性低于private访问说明符。 |
可以在友元功能的帮助下访问private成员。 | public成员可以在有或没有友元功能的帮助下访问。 | protected成员不能通过友元函数访问,它们在类之外是不可访问的,但它们可以被该类的任何子类(派生类),包括派生类及派生类的子类访问。 |
继承方式总结:
class Base {
public:
int x;
protected:
int y;
private:
int z;
};
class PublicDerived: public Base {
// x is public and is accessible in PublicDerived class
// y is protected and is accessible in PublicDerived class
// z is not accessible from PublicDerived, as it is a private member of the base class
};
class ProtectedDerived: protected Base {
// x is protected and is accessible in ProtectedDerived class
// y is protected and is accessible in ProtectedDerived class
// z is not accessible from ProtectedDerived, as it is a private member of the base class
};
class PrivateDerived: private Base {
// x is private and is only accessible by the member functions of the PrivateDerived class
// y is private and is only accessible by the member functions of the PrivateDerived class
// z is not accessible from PrivateDerived, as it is a private member of the base class
};