Make protected inner class public

拟墨画扇 提交于 2019-12-12 05:31:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!