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();
}
相关推荐
不知天地为何吴女士1 小时前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界1 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
wjs20242 小时前
状态模式(State Pattern)
开发语言
我命由我123452 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
励志要当大牛的小白菜4 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970444 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵5 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子6 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男7 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展