Union of same type in C++

后端 未结 3 1857
一向
一向 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: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.

提交回复
热议问题