Forward declaration of nested types/classes in C++

前端 未结 7 1236
刺人心
刺人心 2020-11-22 10:45

I recently got stuck in a situation like this:

class A
{
public:
    typedef struct/class {...} B;
...
    C::D *someField;
}

class C
{
public:
    typedef          


        
7条回答
  •  执笔经年
    2020-11-22 11:19

    This would be a workaround (at least for the problem described in the question -- not for the actual problem, i.e., when not having control over the definition of C):

    class C_base {
    public:
        class D { }; // definition of C::D
        // can also just be forward declared, if it needs members of A or A::B
    };
    class A {
    public:
        class B { };
        C_base::D *someField; // need to call it C_base::D here
    };
    class C : public C_base { // inherits C_base::D
    public:
        // Danger: Do not redeclare class D here!!
        // Depending on your compiler flags, you may not even get a warning
        // class D { };
        A::B *someField;
    };
    
    int main() {
        A a;
        C::D * test = a.someField; // here it can be called C::D
    }
    

提交回复
热议问题