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();
}
相关推荐
Frostnova丶7 小时前
(15)LeetCode 189. 轮转数组
数据结构·算法·leetcode
罗超驿7 小时前
6.Java LinkedList深度解析:从链表原理到源码实践
java·开发语言·链表
2501_948106917 小时前
计算机毕业设计之jsp物业管理系统
java·大数据·开发语言·汽车·课程设计
逝水无殇8 小时前
C# 反射详解
开发语言·后端·c#
Lumos1868 小时前
故障保护与鲁棒性(十七)
算法
阿米亚波8 小时前
【C++ STL】std::list
c++·windows·笔记·stl·list
橙色阳光五月天8 小时前
CMake 构建配置文件解析
c++·cmake·plugin
xlxxy_8 小时前
sap获取批次特性报表
java·linux·开发语言·前端·数据库·abap·mm
手写码匠8 小时前
从零实现大模型推理引擎:Continuous Batching 与动态调度系统深度解析
人工智能·深度学习·算法·aigc
北冥you鱼8 小时前
Go语言常用包使用指南:从标准库到第三方利器
开发语言·microsoft·golang