C++嵌套类转发声明错误

xxx*_*xxx 7 c++ nested class declaration forward

我试图在类A中声明并使用类B并在A之外定义B.
我知道这是可能的,因为Bjarne Stroustrup
在他的书"The C++ programming language"
(例如,第293页)中使用了它String和Srep类).

所以这是导致问题的最小代码

class A{
struct B; // forward declaration
B* c;
A() { c->i; }
};

struct A::B { 
/* 
 * we define struct B like this becuase it
 * was first declared in the namespace A
 */
int i;
};

int main() {
}
Run Code Online (Sandbox Code Playgroud)

此代码在g ++中提供以下编译错误:

tst.cpp: In constructor ‘A::A()’:
tst.cpp:5: error: invalid use of undefined type ‘struct A::B’
tst.cpp:3: error: forward declaration of ‘struct A::B’
Run Code Online (Sandbox Code Playgroud)

我试着看看C++ Faq,我得到的密集在这里这里,
那些不适用于我的情况.
我也是从这里读到的,但它并没有解决我的问题.

gcc和MSVC 2005都会给出编译器错误

CB *_*ley 15

表达式c->i取消引用指针,struct A::B因此在程序中此时必须显示完整定义.

最简单的解决方法是使A非内联构造函数在定义之后为其提供一个主体struct A::B.


Pau*_*ier 11

在结构B的定义之后定义A的构造函数.


e.J*_*mes 7

这是一个很好的例子,说明为什么要将定义与声明分开.您需要更改事物的顺序,以便在A::A()定义之后定义构造函数struct A::B.

class A
{
    struct B;
    B* c;
    A();
};

struct A::B
{
    int i;
};

A::A() { c->i; }

int main()
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)