如何转发声明内部类?
我有一个像这样的类...
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 类的头文件?
I have a class like so...
class Container {
public:
class 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
How can I forward declare this class so I don't have to include the header file that declares the Iterator class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我知道没有办法完全按照你想要的方式做,但如果你愿意使用模板,这里有一个解决方法:
希望这个习惯用法可能对你有一些用处(希望你的编译器是基于 EDG 的并实现导出; ))。
I know of no way to do exactly what you want, but here is a workaround, if you are willing to use templates:
Hopefully, this idiom might be of some use to you (and hopefully your compiler is EDG-based and implements export ;) ).
这根本不可能。 您不能在容器外部转发声明嵌套结构。 您只能在容器内转发声明。
您需要执行以下操作之一:
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
我不相信在不完整的类上向前声明内部类有效(因为如果没有类定义,就无法知道是否确实存在内部类)。 因此,您必须在 Container 的定义中包含一个前向声明的内部类:
然后在相应的源文件中,实现 Container::Iterator:
然后 #include 仅容器标头(或者不担心前向声明,只包含两者) )
I don't believe forward declaring inner class of on an incomplete class works (because without the class definition, there is no way of knowing if there actually is an inner class). So you'll have to include in the definition of Container, a forward declared inner class:
Then in the corresponding source file, implement Container::Iterator:
Then #include only the container header (or not worry about forward declaring and just include both)