问题
I have the following class:
class A
{
protected:
class InnerA {};
};
Now I need to gain access to InnerA class in the tests. Theoretically I could create a test class derived from A and make some parts of A class public. I could do this with fields of course, but not with inner classes.
Is there a way to see the protected InnerA class from outside of A class hierarchy (all classes derived from A)? I would like to be able to write:
Test(MyTest, InnerATest)
{
TestA::InnerA x;
x.DoSth();
}
回答1:
You can inherit and publicize the class, as a matter of fact.
class A
{
protected:
class InnerA {};
};
struct expose : A {
using A::InnerA;
};
int main() {
expose::InnerA ia;
return 0;
}
As you would any other protected member of the base. This is standard C++.
回答2:
If you want to expose a non-public part of class A
for another class or function, you can try with friend
keyword:
class A
{
protected:
friend class B;
friend void f();
int x;
};
class B
{
public:
void sayX()
{
A a;
a.x = 12;
std::cout << a.x << std::endl;
}
};
void f()
{
A a;
a.x = 11;
std::cout << a.x << std::endl;
}
If you want to expose that field to everyone, then I think we're better to put that field to public, or have get/set function for it.
来源:https://stackoverflow.com/questions/44366905/make-protected-inner-class-public