问题描述
我有一个类像这样...
I have a class like so...
class Container {
public:
class Iterator {
...
};
...
};
在其他地方,我想通过引用传递一个Container :: Iterator,但我不想包括头文件。如果我试图转发声明类,我得到编译错误。
Elsewhere, I want to pass a Container::Iterator by reference, but I don't want to include the header file. If I try to forward declare the class, I get compile errors.
class Container::Iterator;
class Foo {
void Read(Container::Iterator& it);
};
编译上述代码给出...
Compiling the above code gives...
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类的头文件? p>
How can I forward declare this class so I don't have to include the header file that declares the Iterator class?
推荐答案
这根本不可能。您不能向容器外部声明一个嵌套结构。您只能转发在容器中声明它。
This is simply not possible. You cannot forward declare a nested structure outside the container. You can only forward declare it within the container.
您需要执行以下操作之一
You'll need to do one of the following
- 非嵌套
- 更改声明顺序,以便嵌套类首先完全定义
- 创建一个公共基类,函数并由嵌套类实现。
这篇关于如何转发声明一个内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!