使用类时,受保护成员和私有成员之间确实没有区别。任何使用该类的东西都无法访问。
class A {
private: int privateNum;
protected: int protectedNum;
public: int publicNum;
void SetNumbers(int num) {
privateNum = num; //valid, private member can be accessed in member function
protectedNum = num; //valid, protected member can be accessed in member function
}
};
void main() {
A classA;
classA.privateNum = 1; //compile error can't access private member
classA.protectedNum = 1; //compile error can't access protected member
classA.publicNum = 1; //this is OK
classA.SetNumbers(1); //this sets the members not accessible directly
}
当您从具有受保护成员的类继承时,差异就会生效。
class B : public A {
};
基类的所有私有成员仍然是私有的,派生类将无法访问。另一方面,受保护的成员可以被继承的类访问,但在继承的类之外仍然无法访问。
class B : public A {
public:
void SetBNumbers(int num) {
privateNum = num; //compile error, privateNum can only be accessed by members of A, not B
protectedNum = num; //this works, as protected members can be accessed by A and B
}
};
void main() {
B classB;
classB.publicNum = 1; //valid, inherited public is still public
classB.protectedNum = 1; //compile error, can't access protected member
classB.privateNum = 1; //compile error, B doesn't know that privateNum exists
classB.SetBNumbers(1); //this sets the members not accessible directly
}