我有这样的课......
class Container {
public:
class Iterator {
...
};
...
};
在其他地方,我想通过引用传递一个 Container::Iterator,但我不想包含头文件。如果我尝试转发声明该类,则会出现编译错误。
class Container::Iterator;
class Foo {
void Read(Container::Iterator& it);
};
编译上面的代码给出...
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
如何转发声明这个类,这样我就不必包含声明 Iterator 类的头文件?
最佳答案
这根本不可能。您不能在容器外转发声明嵌套结构。您只能在容器内转发声明它。
您需要执行以下操作之一
- 使类非嵌套
- 更改您的声明顺序,以便首先完全定义嵌套类
- 创建一个既可以在函数中使用又可以由嵌套类实现的通用基类。
关于c++ - 如何转发声明内部类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1021793/