1 class BaseClass 2 { 3 public: 4 int public_int; 5 private: 6 int private_int; 7 protected: 8 int protected_int; 9 }; 10 11 class DerivedClass :public BaseClass { 12 public: 13 void UsePublicInt() 14 { 15 public_int = 1; //正确 16 } 17 void UserPrivateInt() 18 { 19 private_int = 1;//错误:成员 BaseClass::private_int不可访问 20 } 21 void UserProtectedInt() 22 { 23 protected_int = 1; //正确 24 } 25 }; 26 27 //protected 对ProtectedDerivedClass的派生类和用户和友元函数产生影响,对ProtectedDerivedClass自身的成员函数无影响 28 class ProtectedDerivedClass :protected BaseClass { 29 public: 30 void UsePublicInt() 31 { 32 public_int = 1; //正确 BaseClass::public_int是公有的 33 } 34 void UserPrivateInt() 35 { 36 private_int = 1;//错误:成员 BaseClass::private_int不可访问 37 } 38 void UserProtectedInt() 39 { 40 protected_int = 1; //正确 41 } 42 }; 43 44 int main() 45 { 46 BaseClass baseclass; 47 baseclass.public_int; //正确 48 baseclass.protected_int; //错误:成员 BaseClass::protected_int不可访问 49 baseclass.private_int; //错误:成员 BaseClass::private_int不可访问 50 51 DerivedClass derivedclass; 52 derivedclass.public_int; //正确 53 derivedclass.protected_int; //错误:成员 BaseClass::protected_int不可访问 54 derivedclass.private_int; //错误:成员 BaseClass::private_int不可访问 55 56 ProtectedDerivedClass protectedderivedclass; 57 protectedderivedclass.public_int = 1;//错误:成员 BaseClass::public_int不可访问 原因 ProtectedDerivedClass :protected DerivedClass,对ProtectedDerivedClass的用户而言public_int是protectd,所以无法访问 58 protectedderivedclass.protected_int; //错误:成员 BaseClass::protected_int不可访问 59 protectedderivedclass.private_int; //错误:成员 BaseClass::private_int不可访问 60 }