クラスを利用する場合、保護されたメンバーとプライベートメンバーの間に違いはありません。クラスを利用するものにはアクセスできません。
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
}
ありがとうございました!私は今私の間違いを見る –