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();
}
相关推荐
pps-key30 分钟前
网络攻防入门:从“黑客梦”到合法实操(生存篇)
开发语言·web安全·php
罗西的思考36 分钟前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(2)
人工智能·算法·机器学习
罗西的思考39 分钟前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(1)
人工智能·算法·机器学习
汤姆宝库1 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
武子康2 小时前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习
驭渊的小故事3 小时前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
南风84114 小时前
C++ 四种强制类型转换详解
c++
Sakura_j_h_4 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
微笑星河q4 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
Eider19985 小时前
Python基础语法之并发相关3
开发语言·python