给struct或union成员两个名称,其中一个用数组元素表示


#include <iostream>

struct Point2d
{
	union
	{
		float pos[3];
		struct
		{
			float x, y, w;
		};
	};
};

void main()
{
	// 1.pos[]数组和x, y, w使用同一片区域,这就使每个分量有了两个名字pos[0] = x, pos[1] = y, pos[2] = w
	Point2d p2d = {};
	for (unsigned i = 0; i < 3; i++)
		p2d.pos[i] = float(i + 1);
	std::cout << p2d.x << ", " << p2d.y << ", " << p2d.w << std::endl;
	// 至于为什么要让三者连续存储,因为方便它与变换矩阵的计算中能够使用下标进行循环。

	// 2.初始化列表直接初始化
	Point2d p2d2 = {3, 2, 1};
	std::cout << p2d2.x << ", " << p2d2.y << ", " << p2d2.w << std::endl;

	// 3.直接用union
	union Point2d_U
	{
		struct 
		{
			float x, y, w;
		};
		float pos[3];
	};

	// 3.1.
	Point2d_U p2du = {};
	for (unsigned i = 0; i < 3; i++)
		p2du.pos[i] = float(i + 1);
	std::cout << p2du.x << ", " << p2du.y << ", " << p2du.w << std::endl;

	// 3.2.
	Point2d_U p2du2 = {3, 2, 1};
	std::cout << p2du2.x << ", " << p2du2.y << ", " << p2du2.w << std::endl;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值