求教,c++: struct 和 union 混合使用的问题

latecho 2012-07-05 05:55:15
最近作业需要模拟解码器,所以采用bit field的思想,构建了如下结构并且进行简单测试(请忽略很多非struct INS_COMP相关的问题)
#include <stdio.h>

struct INS_COMP
{
unsigned int opCode:6;
union
{
struct A
{
union
{
unsigned int rd:5;
unsigned int cond_6_10:5;
};
union
{
unsigned int ra:5;
unsigned int cond_11_15:5;
};
unsigned int rb:5;
union
{
unsigned int imm:11;
unsigned int cond_21_31:11;
};
};
struct B
{
union
{
unsigned int rd:5;
unsigned int cond_6_10:5;
};
union
{
unsigned int ra:5;
unsigned int cond_11_15:5;
};
union
{
unsigned int imm:16;
unsigned int cond_21_31:16;
struct res_cond_imm
{
unsigned int reserve:5;
unsigned int cond:6;
unsigned int imm:5;
};
};
};
};
}I;

int main()
{
std::cout << I.A.imm;
}

出现如下错误:
44 `struct INS_COMP::<anonymous union>::B::<anonymous union>::res_cond_imm' invalid; an anonymous union can only have non-static data members

9 struct INS_COMP::<anonymous union>::A' invalid; an anonymous union can only have non-static data members

28 struct INS_COMP::<anonymous union>::B' invalid; an anonymous union can only have non-static data members

使用Google和百度也搜索了一些文章阅读,但是始终没有像明白,还请高手稍微指点一下。
...全文
335 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Corner 2012-07-05
  • 打赏
  • 举报
回复
你的共用体也是匿名的,共用体在某些编译器下可以匿名,但是不是C99标准,所以最好也有名字,否则遵循C99标准的编译器下上面代码会报错。
一叶之舟 2012-07-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
C/C++ code


struct INS_COMP
{
unsigned int opCode:6;
union
{
struct A
{
union
{
unsigned int rd:5;
uns……
[/Quote]
不要有匿名的成员变量。
Corner 2012-07-05
  • 打赏
  • 举报
回复
你既然知道给struct INS_COMP变量命名为I,怎么没想到给Struct A的变量命名呢……

struct A
{
union
{
unsigned int rd:5;
unsigned int cond_6_10:5;
};
union
{
unsigned int ra:5;
unsigned int cond_11_15:5;
};
unsigned int rb:5;
union
{
unsigned int imm:11;
unsigned int cond_21_31:11;
};
}A;//增加变量名,避免anonymous
Corner 2012-07-05
  • 打赏
  • 举报
回复


struct INS_COMP
{
unsigned int opCode:6;
union
{
struct A
{
union
{
unsigned int rd:5;
unsigned int cond_6_10:5;
};
union
{
unsigned int ra:5;
unsigned int cond_11_15:5;
};
unsigned int rb:5;
union
{
unsigned int imm:11;
unsigned int cond_21_31:11;
};
}A;
struct B
{
union
{
unsigned int rd:5;
unsigned int cond_6_10:5;
};
union
{
unsigned int ra:5;
unsigned int cond_11_15:5;
};
union
{
unsigned int imm:16;
unsigned int cond_21_31:16;
struct res_cond_imm
{
unsigned int reserve:5;
unsigned int cond:6;
unsigned int imm:5;
};
};
}B;
};
}I;

struct A是类型,所以你的两个结构体成员都没有命名,所以会报错,给他们起个名字就好了

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧