Union of same type in C++

后端 未结 3 1856
一向
一向 2021-01-17 23:06

Whenever I see examples of union, they are always different types. For example, from MSDN:

// declaring_a_union.cpp
union DATATYPE    // Declare union type
{         


        
相关标签:
3条回答
  • 2021-01-17 23:32

    No, this won't cause any issues. The reason you don't see it more often is that it's pointless - both names refer to the same value of the same type.

    0 讨论(0)
  • 2021-01-17 23:39

    This is legal and very useful in situations where you have different contexts, where different names would be more appropriate. Take a four member vector vec4 type for example (similar to what you'd find in GLSL):

    vec4 v(1., 1., 1., 1.);
    
    // 1. Access as spatial coordinates
    v.x;
    v.y;
    v.z;
    v.w;
    
    // 2. Access as color coordinates (red, green, blue, alpha)
    v.r;
    v.g;
    v.b; 
    v.a;
    
    // 3 Access as texture coordinates
    v.s;
    v.t;
    v.p;
    v.q;
    

    A vec4 may only have four members of the same type, but you'd use different names to refer to the same objects, depending on the context.

    0 讨论(0)
  • 2021-01-17 23:44

    An issue would arise only if you want to have unique values for the two variables. In your use-case, it should work fine.

    0 讨论(0)
提交回复
热议问题