#include <iostream>
class Base
{
protected:
void somethingProtected()
{
std::cout << "lala" << std::endl;
}
};
class Derived : public Base
{
public:
void somethingDerived()
{
Base b;
b.somethingProtected(); // This does not compile
somethingProtected(); // But this is fine
}
};
int main()
{
Derived d;
d.somethingDerived();
return 0;
}
this
の保護されたメンバーのみを使用でき、他のインスタンスの保護されたメンバーには永遠に到達できないのではないかと思いました。
しかし:
class Derived : public Base
{
public:
void somethingDerived(Derived& d)
{
d.somethingProtected(); // This compiles even though d is
// potentially a different instance
}
void somethingDerived(Base& b)
{
b.somethingProtected(); // This does not
}
};
私はしばらく C++ でプログラミングを行ってきたので、これには吐き気がしますが、この動作の説明が見つかりませんでした。
編集:
同じか別のインスタンスかは問題ではありません。
int main()
{
Derived d1, d2; // Two different instances
d1.somethingDerived(d2); // This compiles fine
d1.somethingDerived(d1); // This compiles fine
return 0;
}
EDIT2:
アクセス権に関しては、クラスのどのインスタンスが使用されているかはまったく問題ではないようです。
class Base
{
public:
void something(Base& b) // Another instance
{
++b.a; // But can enter private members
}
private:
int a;
};