对同一个数组数据,提供多种操作方法。看栗子。
#include <isotream>
int main()
{
struct A
{
union
{
float a;
int b;
}
};
A e;
A.a = 2;
std::cout<<A.a<<","<<A.b<<endl;
std::cin.get();
}
打印出的是2,1703741824
2是浮点的2,1703741824是浮点形式的2的字节表示,就是取得了浮点2的内存将其解释成整型。
这就与上一个笔记中的类型转换相对应了。
我们可以看到我对于b并没与做什么变化,却已经与2转换了类型,意味着union内部其实只有一个成员,两个变量指向了一个地址。我们再来看个栗子。
#include <iostream>
#inclued <vector>
struct Vector2
{
float x,y;
};
struct Vector4
{
float x,y,z,w;
};
void PrintfVector2(const Vector2& vector)
{std::cout<<vector.x<<","<<vector.y<<endl;}
int main()
{
sad::cin.get();
}
我们看到思维向量实际上就是两个二维向量,那怎么用两个Vector2表示一个Vector4呢?我们可以设计两个二维向量a b,其中a对应着四维的xy,b对应着四维的zw。
#include <iostream>
#inclued <vector>
struct Vector2
{
float x,y;
};
struct Vector4
{
union
{
struct
{
float x,y,z,w;
};
}
};
void PrintfVector2(const Vector2& vector)
{std::cout<<vector.x<<","<<vector.y<<endl;}
int main()
{
sad::cin.get();
}
我们对四维向量做出以上改变,注意到struct实际上没有对其命名(匿名结构体)将xyzw结构体作为一个成员放在union中。为什么这么做?还记说union只有一个成员,如果不用匿名结构体,那么xyzw指向的都是一个地址,这显然是不对的。
我们继续的代码更改。
#include <iostream>
#inclued <vector>
struct Vector2
{
float x,y;
};
struct Vector4
{
union
{
struct
{
float x,y,z,w;
};
struct
{
vector a,b;
};
}
};
void PrintfVector2(const Vector2& vector)
{std::cout<<vector.x<<","<<vector.y<<endl;}
int main()
{
Vector4 vector = {1.0f,2.0f,3.0f,4.0f};
PrintfVector2(a);
PrintfVector2(b);
vector.z = 99;
PrintfVector2(a);
PrintfVector2(b);
sad::cin.get();
}
union下a与xy占据相同内存,b与zw占据相同内存,就是我们有两个方式操纵四维变量。
打印效果为
1,2
3 , 4
1,2
99 , 4
union为我们提供了对于相同变量进行不同方式操作的关键字。