【问题标题】:Compiling error when using struct within an inner class在内部类中使用结构时编译错误
【发布时间】:2016-11-26 22:58:59
【问题描述】:

我找不到任何可以帮助我理解为什么以下代码无法编译的答案。 我在类 (Foo) 的私有部分中声明了一个结构,并尝试在这样的内部类 (Bar) 中使用它。

class Foo {
public:
    Foo();
    class Bar;

    class Bar {
    public:
        Bar();
        Foo::Node createNode();
    };

private:
     struct Node{
        Node(int d) : data(d) {};
        int data;
     };
};

并且编译器抛出以下错误:

.../Foo.h:9:14: error: no type named 'Node' in 'Foo'

【问题讨论】:

  • C(++) 编译器从上到下读取,如果在某一行没有定义类型(因为它是在之后定义的),则无法引用它。解决方法:将struct node的定义移到class bar的定义之上。顺便说一句:如果你有这个结构私有,你会收到另一个关于可见性的错误。

标签: c++


【解决方案1】:

你需要在引用它之前声明内部类:

class Foo {
    class Node;
public:

    // ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2013-12-06
    相关资源
    最近更新 更多