union实用方法

来源:互联网 发布:交大知行论坛 编辑:程序博客网 时间:2024/06/06 04:11

union是中再简单不过的结构,其用法也相当单一。

 

定义一个2×2的矩阵,union的作用使struct里的元素和float类型的数组值一一对应,可以相互代表。

// 2x2 matrix /////////////////////////////////////////////

typedef struct MATRIX2X2_TYP

{

union

    {

    float M[2][2]; // array indexed data storage

 

    // storage in row major form with explicit names

    struct

         {

         float M00, M01;

         float M10, M11;

         }; // end explicit names

 

     }; // end union

} MATRIX2X2, *MATRIX2X2_PTR;

 

用向量代替某列

// matrix and vector column swaping macros

inline void MAT_COLUMN_SWAP_2X2(MATRIX2X2_PTR m, int c, MATRIX1X2_PTR v)

{

         m->M[0][c]=v->M[0];

         m->M[1][c]=v->M[1];

}

 

 

2×2矩阵乘法

void Mat_Mul_2X2(MATRIX2X2_PTR ma, MATRIX2X2_PTR mb, MATRIX2X2_PTR mprod)

{

// this function multiplies two 2x2 matrices together and

// and stores the result in mprod

mprod->M00 = ma->M00*mb->M00 + ma->M01*mb->M10;

mprod->M01 = ma->M00*mb->M01 + ma->M01*mb->M11;

 

mprod->M10 = ma->M10*mb->M00 + ma->M11*mb->M10;

mprod->M11 = ma->M10*mb->M01 + ma->M11*mb->M11;

 

} // end Mat_Mul_2X2

 

这个4元数里排了两个struct

typedef struct QUAT_TYP

{

union

    {

    float M[4]; // array indexed storage w,x,y,z order

 

    // vector part, real part format

    struct

         {

         float    q0;  // the real part

         VECTOR3D qv;  // the imaginary part xi+yj+zk

         };

    struct

         {

         float w,x,y,z;

         };

    }; // end union

 

} QUAT, *QUAT_PTR;

 

 

可见,如此使用union,对提高程序的清晰性以及减小复杂性是很有效的。