c++ - 如何转发声明内部类?

标签 c++ forward-declaration

<分区>

我有一个这样的类......

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 类的头文件?

最佳答案

这根本不可能。您不能在容器外转发声明嵌套结构。您只能在容器内转发声明它。

您需要执行以下操作之一

  • 使类成为非嵌套的
  • 更改您的声明顺序,以便首先完全定义嵌套类
  • 创建一个既可以在函数中使用又可以由嵌套类实现的公共(public)基类。

关于c++ - 如何转发声明内部类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34731205/

相关文章:

c++ - 这将打印出什么,为什么?你会怎么修? [C++]

c++ - MSVC++ 中的无限

c - 前向声明如何运作?

c++ - C++ 中带有对象名称的 typedef 结构的前向声明

javascript - 为什么我不能在 try block 中定义之前使用 Javascript 函数?

c++ - std::bind 头文件声明

c++ - 按特定值按升序对字符串进行排序。我的实现有什么问题?

c++ - 如何使用 rad studio 显示窗口总数?

c - typedef 结构、循环依赖、前向定义

c++ - 错误 : forward declaration, 如何访问指针