#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;
}