可能重复:
在C++中转发嵌套类型/类的声明
我有一个这样的课......
class Container {
public:
class Iterator {
...
};
...
};
Run Code Online (Sandbox Code Playgroud)
在其他地方,我想通过引用传递一个Container :: Iterator,但我不想包含头文件.如果我尝试转发声明类,我会遇到编译错误.
class Container::Iterator;
class Foo {
void Read(Container::Iterator& it);
};
Run Code Online (Sandbox Code Playgroud)
编译上面的代码给出了......
test.h:3: error: ‘Iterator’ in class ‘Container’ does not name a type
test.h:5: error: variable or field ‘Foo’ declared void
test.h:5: error: incomplete type ‘Container’ used in nested name specifier
test.h:5: error: ‘it’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
我怎样才能转发声明这个类,所以我不必包含声明Iterator类的头文件?
假设我有一个类F
应该是类G
(在全局命名空间中)和C
(在命名空间中A
)的朋友.
A::C
,F
必须向前宣布.G
,没有F
必要的前瞻性声明.A::BF
可以成为朋友而A::C
无需前瞻性声明下面的代码说明了这一点,并使用GCC 4.5,VC++ 10以及至少与另一个编译器进行编译.
class G {
friend class F;
int g;
};
// without this forward declaration, F can't be friend to A::C
class F;
namespace A {
class C {
friend class ::F;
friend class BF;
int c;
};
class BF {
public:
BF() { c.c = 2; }
private:
C c;
};
} // …
Run Code Online (Sandbox Code Playgroud) 我只是从http://www.cplusplus.com/doc/tutorial/namespaces/上阅读了一些内容 ,它看起来像一个结构体能够做同样的事情?或者甚至是一个类.也许有人可以更好地定义命名空间是什么,以及它与结构/类的区别?