【发布时间】:2023-03-25 04:45:01
【问题描述】:
我正在尝试在 A 类中声明和使用 B 类
并在 A 之外定义 B。
我知道这是可能的,因为 Bjarne Stroustrup
在他的《C++ 编程语言》一书中使用了这一点
(第 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() {
}
此代码在 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’
我试图查看 C++ 常见问题解答,我得到的最接近的是 here 和 here 但是
这些不适用于我的情况。
我也从这里read this,但这并没有解决我的问题。
gcc 和 MSVC 2005 都给出了编译器错误
【问题讨论】:
标签: c++ class nested declaration forward