匿名联盟只能拥有非静态数据成员GCC c ++

时间:2013-07-14 07:20:34

标签: c++ gcc

我有一些C代码并使用GCC编译器。

代码在匿名联合中有一些嵌套类型:

struct ab {
    int a;
    int b;
    union {
        int *c;
        int *d;
        struct f {
           int *c;
           int *d;
        };
        struct e {
            int *c;
            int *d;
        };
    };
};

我收到此错误:

Error: 'struct ab::<anonymous union>::f' invalid; an anonymous union 
can only have non-static data members.

有人可以进一步解释为什么会发生这种错误吗?

3 个答案:

答案 0 :(得分:5)

好吧,您不能在匿名联合中声明嵌套类型。这正是您所做的:您在匿名联盟中声明了类fe。这是编译器不喜欢的。它告诉你,在匿名联合中你可以做的就是声明非静态数据成员。你不能在那里声明嵌套类型。

目前尚不清楚你要在这里做什么,所以很难提供任何进一步的建议。

答案 1 :(得分:4)

删除union中struct的定义。

struct ab {
    int a;
    int b;
    union {
        int *c;
        int *d;
        struct  {
           int *c;
           int *d;
        };
        struct {
            int *c;
            int *d;
        };
    };
};

答案 2 :(得分:0)

引用union成员时,它就像一个struct成员。您为编译器创建了一个模糊的情况。

以下是有关GCC规范的更多信息:http://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html#Unnamed-Fields

How to compile C code with anonymous structs / unions?

相关问题