How to access the protected member if we cannot modify the class?
The third party library's class contains a protected member. How can I access it if we cannot modify the cod开发者_如何学Goe of the third party library?
A protected member can only be accessed by the class itself, subclasses, or friend classes and methods. The only way to access the protected member is to subclass the class, then use your subclass to expose the protected member.
Eg:
class parent {
/* Other members */
protected:
int foo();
}
class child : public parent {
public:
int foo();
}
You should make a special wrapper for that class. Just inherit library's class and gain the access to protected members. Due to inheritance, it is possible to use the wrapper class instead of the base class in your following code.
You can access protected members from a derived class.
class A
{
protected:
int i;
};
class B : public A
{
void func()
{
i; //valid
}
};
精彩评论