c++ Union之妙用

union的作用基本是它里面的变量都用了同一块内存,跟起了别名一样,类型不一样的别名。

基本用法:

cpp 复制代码
	struct Union
	{
		union {
			float a;
			int b;
		};
	};

	Union u;
	u.a = 2.0f;

	std::cout << u.a << "," << u.b << std::endl;

常规用法,见结构体:

cpp 复制代码
#include <iostream>
#include <string>
#include <vector> 
#include <algorithm> /* sort*/
#include <functional> /*std::greater<int>()*/
#include "game.h"
 
struct Vector2 {
	float x, y;
};

struct Vector4
{
	/*因使用union方法,故先注释掉*/
	// float x, y, z, w;

	//Vector2 GetA() { /*这样的方法将会创建一个新的对象,我们不想这么做*/
	//	return Vector2(); 
	//}

	/*一种方法*/
	/*Vector2& GetA() {  
		return *(Vector2*)&x;
	}*/

	/*但是如果使用Union的话可能就要好的多*/
	union {
		// float x, y, z, w; /*如果这么写的话是不行的,因为四个值用的同一块内存*/

		/*解决办法是用结构体,这里union和struct都没有名字,他们都是匿名函数*/
		struct 
		{
			float x, y, z, w;
		};

		/*这里再向union添加另一个结构体,显然他们是占用同一块内存的
		这里就体现了Union的用处*/
		struct {
			Vector2 a, b;
		};
	};
};

void PrintVector2(const Vector2& vector2) {
	std::cout << vector2.x << " " << vector2.y << std::endl;
}

int main() {
	 
	Vector4 vector = { 1.0f, 2.0f, 3.0f, 4.0f };
	std::cout << vector.x << std::endl; /*可以看到,还是可以访问x的*/
	PrintVector2(vector.a);
	PrintVector2(vector.b);
	vector.z = 500.0f;
	PrintVector2(vector.a);
	PrintVector2(vector.b);

	struct Union
	{
		union {
			float a;
			int b;
		};
	};

	Union u;
	u.a = 2.0f;

	std::cout << u.a << "," << u.b << std::endl;
	
	/*测试game*/
	// game::runGame();

	std::cin.get();
}
相关推荐
MicroTech2025几秒前
微算法科技(NASDAQ :MLGO)量子生成对抗网络(QGAN)技术,为网络安全防御提供了全新的技术路径
科技·算法·生成对抗网络
leaves falling2 分钟前
c语言-编译和链接
c语言·开发语言
YuTaoShao3 分钟前
【LeetCode 每日一题】3507. 移除最小数对使数组有序 I
算法·leetcode·职场和发展
kk5793 分钟前
【MATLAB R2018a】路径文件pathdef.m为只读文件无法保存到matlab启动文件夹的问题
开发语言·matlab
黎雁·泠崖4 分钟前
Java静态变量底层:内存图解析+避坑指南
java·开发语言
布局呆星6 分钟前
魔术方法与魔术变量
开发语言·python
Gary董7 分钟前
java死锁
java·开发语言
陳103010 分钟前
C++:多态
开发语言·c++
LYS_061817 分钟前
RM赛事C型板九轴IMU解算(3)(姿态融合算法)
c语言·算法·imu·姿态解算·四元数到欧拉角
LDG_AGI20 分钟前
【机器学习】深度学习推荐系统(三十一):X For You Feed 全新推荐系统技术架构深度解析
人工智能·深度学习·算法·机器学习·架构·推荐算法