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();
}
相关推荐
Ludicrouers3 分钟前
【Leetcode-Hot100】移动零
算法·leetcode·职场和发展
rigidwill6667 分钟前
LeetCode hot 100—最长回文子串
数据结构·c++·算法·leetcode·职场和发展
小林熬夜学编程8 分钟前
【高阶数据结构】第二弹---图的深度解析:从基本概念到邻接矩阵的存储与操作
c语言·数据结构·c++·算法·深度优先·图论
xlcoding1 小时前
位掩码、哈希表、异或运算、杨辉三角、素数查找、前缀和
c++·算法·蓝桥杯
alive9031 小时前
【QT】 进程
c++·qt·嵌入式·进程·qprocess
Blood_J2 小时前
python网络爬虫
开发语言·爬虫·python
小开不是小可爱2 小时前
leetcode_383. 赎金信_java
java·数据结构·算法·leetcode
xiaowu0803 小时前
C# task任务异步编程提高UI的响应性
开发语言·c#
kill bert5 小时前
Java八股文背诵 第四天JVM
java·开发语言·jvm
√尖尖角↑6 小时前
力扣——【1991. 找到数组的中间位置】
算法·蓝桥杯