union实用方法

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,对提高程序的清晰性以及减小复杂性是很有效的。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值