當使用一個類時,保護和私有成員之間確實沒有區別。任何利用課堂的東西都不能訪問。
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
}
謝謝!我現在看到我的錯誤 – 2009-06-08 22:41:27