C++でのprotectedの使い方はどうですか。
C++において、protectedキーワードはクラスのメンバー変数やメソッドを宣言するために使用され、これらのメンバーはクラスの派生クラスからアクセス可能ですが、クラスのオブジェクトからは直接アクセスできません。
protectedキーワードを使用すると、protectedメンバーにアクセスできるのはクラス内部および派生クラスに限られます。例を以下に示します:
class Base {
protected:
int protectedVar;
public:
Base() {
protectedVar = 10;
}
void printProtectedVar() {
cout << "Protected Variable: " << protectedVar << endl;
}
};
class Derived : public Base {
public:
void modifyProtectedVar() {
protectedVar = 20;
cout << "Modified Protected Variable: " << protectedVar << endl;
}
};
int main() {
Base obj;
obj.printProtectedVar(); // 在类的成员函数中访问protected成员
Derived derivedObj;
derivedObj.modifyProtectedVar(); // 在派生类的成员函数中访问protected成员
return 0;
}
この例では、BaseクラスでprotectedVarというprotectedメンバ変数が宣言され、そのメンバ変数にアクセスするためのメンバ関数printProtectedVarが定義されています。DerivedクラスはBaseクラスを継承し、protectedVarの値を変更するためのメンバ関数modifyProtectedVarを定義しています。main関数では、BaseクラスのobjオブジェクトとDerivedクラスのderivedObjオブジェクトが作成され、それぞれのメンバ関数が呼び出されてprotectedメンバにアクセスおよび変更されています。