当前位置: 首页 > news >正文

52. 类型双关union

目录

52.1 类型双关 

52.2 union


52.1 类型双关 

 将一个int类型转为double类型,有如下方式

int main() {
	int a = 5;
	double b = a;//隐式类型转换
	double c = (double)a;//显示类型转换
	double d = *(double*)&a;//类型双关:将类型int的内存操作为double
	//打印a 5 b:5 c:5 d:-9.25596e+61
	std::cout << "a " << a << " b:" << b << " c:" << c << " d:" << d << std::endl;
	std::cin.get();
}

可以看到,类型双关的操作先把一个int类型指针转为double类型指针,然后解引用。结果是在原来的int内存之后继续了4个字节,然后获取整个内存,结果打印的地址并不理想,有可能造成崩溃,这样的类型双关操作不安全。下面演示安全的类型双关操作:

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>

struct Entity
{
	int x, y;
	int* getStartPosition()
	{
		return &x;
	}
};

int main() {
	Entity e = { 1,2 };
    //方式一
	int* position = (int*)&e;//结构体转为数组
	std::cout << position [0]<< ","<<position[1] << std::endl;//打印1,2
	//方式二
	int* position2 = e.getStartPosition();
	std::cout << position2[0] << "," << position2[1] << std::endl;//打印1,2
	int y = *(int*)((char*)&e + 4);//通常使用y = e.y;来访问
	std::cout << y << std::endl;//打印2
	std::cin.get();
	return 0;
}

可以看到我们能够自如的操作c++的内存,同一块内存进行不同类型之间的转换,这就是类型双关。需要做的就是将原来的指针转换为另一个类型的指针(结构体e的指针转化为数组的起始指针),然后作为另一种类型去访问它(作为数组类型去访问)。

52.2 union

union关键字使得不同类型成员变量共享同一块内存,这运用了类型双关的概念

//
//  main.cpp
//  HelloWorld
//
//  Created by  on 2024/11/28.
//

#include <iostream>

struct vector2
{
	float x, y;

};
struct vector4 {
	union {
		struct
		{
			float x, y, z, w;
		};
		struct
		{
			vector2 a, b;//a对应x,y;b对应z,w
		};
	};//union中的各个成员占用同一块内存
};
void printVector2(const vector2 &v)
{
	std::cout << v.x << "," << v.y << std::endl;
}
int main(int argc, const char * argv[]) {
	vector4 v = { 1.0f,2.0f,3.0f,4.0f };
	printVector2(v.a);
	printVector2(v.b);
	v.z = 5;
	std::cout <<  "-------------" <<  std::endl;
	printVector2(v.a);
	printVector2(v.b);
}

打印结果如下: 

 

相关文章:

  • 使用vue3框架vue-next-admin导出表格excel(带图片)
  • 获取钉钉OA审批数据
  • AI工作流+专业知识库+系统API的全流程任务自动化
  • java练习(33)
  • zookeeper集群配置
  • SAP:SAP的内存管理详解
  • C++ 模板 简单易懂
  • 使用 acme.sh 申请和管理 免费SSL 证书:告别 certbot 的繁琐
  • 【数据挖掘】深度挖掘
  • vue3-05reactive定义对象类型的响应式数据(不能进行基本类型数据的响应式)
  • 聚焦于机器人研究,提出 FuSe 方法,通过语言锚定对通用机器人策略进行微调 视觉、触觉、听觉
  • ET框架实现匹配功能(服务器端)
  • TArray系列(二)
  • 【linux】文件与目录命令 - grep
  • UNIAPP开发之利用阿里RTC服务实现音视频通话后端THINKPHP5
  • 磐维数据库双中心容灾流复制集群搭建
  • K8S下redis哨兵集群使用secret隐藏configmap内明文密码方案详解
  • 我的文具盒作文范文
  • windows使用命令解压jar包,替换里面的文件。并重新打包成jar包,解决Failed to get nested archive for entry
  • 软件单元测试的技术要求
  • 上海发布预付卡消费“10点提示”:警惕“甩锅闭店”套路
  • 常州市委原常委、组织部部长陈翔调任江苏省民宗委副主任
  • 马上评|不再提“智驾”,新能源车企回归理性
  • 观察|印巴交火开始升级,是否会升级为第四次印巴战争?
  • 外交部:印巴都表示不希望局势升级,望双方都能保持冷静克制
  • 中国证监会:帮助受关税政策影响较大的上市公司纾困解难