简体   繁体   English

在 C++ 中访问联合内的结构时出现问题

[英]Issue in accessing a structure inside a union in C++

   union hello
   {
      struct hi
      {
         uint8_t trees;
         uint8_t plants[6];
      };
      uint8_t forest[1 + 6];
   };

   struct world
   {
      hello a;
   };

typedef std::vector<world> universe;
universe alpha;

if I want to access the structure hi inside hello, then I am doing something like, assuming accessing the 1st vector element如果我想访问 hello 里面的结构 hi ,那么我正在做类似的事情,假设访问第一个向量元素

alpha.at(1).a.hi.trees = 1; // error in accessing "hi" , why can't I access hi like this?  

ERROR: type name is not allowed错误:不允许使用类型名称

the struct is not a field of union in your version;在您的版本中,该struct不是联合字段; it's just nested type name.它只是嵌套类型名称。 change it to this:将其更改为:

   union hello
   {
      struct
      {
         uint8_t trees;
         uint8_t plants[6];
      } hi;/*<< put the field name here*/
      uint8_t forest[1 + 6];
   };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM