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

c++ Union之妙用

union的作用基本是它里面的变量都用了同一块内存,跟起了别名一样,类型不一样的别名。
基本用法:

	struct Union{union {float a;int b;};};Union u;u.a = 2.0f;std::cout << u.a << "," << u.b << std::endl;

常规用法,见结构体:

#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();
}
http://www.lryc.cn/news/134513.html

相关文章:

  • JSON的处理
  • matlab使用教程(20)—插值基础
  • Python功能制作之简单的3D特效
  • leetcode-5-最长回文串
  • 二、Oracle 数据库安装集
  • 【Python】Python中的常用函数及用法
  • 基于JavaEE的ssm公司员工信息管理系统的设计与实现
  • cornerstoneJS加载图片(base、矩阵)
  • 3.Trunc截断函数用法
  • 腾讯云 CODING 荣获 TiD 质量竞争力大会 2023 软件研发优秀案例
  • VSCode如何为远程安装预设(固定)扩展
  • 一文解析HTTP与HTTPS,它们的区别和联系
  • Faster RCNN网络数据流总结
  • 拒绝摆烂!C语言练习打卡第五天
  • 关于LambdaQueryWrapper.or()导致错误
  • Day17-Node后端身份认证-JWT
  • onvif中imaging setting图像画质总结!
  • not in效率低(MYSQL的Not IN、not EXISTS如何优化)
  • 微信小程序拉起支付报: 调用支付JSAPI缺少参数: total_fee
  • Thinkphp6 如何 生成二维码
  • 01.机器学习引言
  • 结构型(二) - 桥接模式
  • 多维时序 | MATLAB实现WOA-CNN-GRU-Attention多变量时间序列预测
  • C#与西门子PLC1500的ModbusTcp服务器通信1--项目背景
  • Socks5代理与IP代理:网络安全与爬虫之道
  • 苹果电脑怎么录屏?步骤详解,看到就是赚到
  • vb毕业生管理系统设计与实现
  • WPF入门到精通:4.页面增删改查及调用接口(待完善)
  • 容器和云原生(三):kubernetes搭建与使用
  • spring boot集成jasypt 并 实现自定义加解密