day16

目录

[1 联合体的定义和使用](#1 联合体的定义和使用)

[2 联合体的内存布局](#2 联合体的内存布局)

[3 联合体的应用](#3 联合体的应用)


1 联合体的定义和使用

cpp 复制代码
#include <iostream>

using namespace std;

struct DataS
{
	int i;	
	double d;	
	char s[10];	
	
};

/*
	联合体 所有成员共享同一段内存  
		   修改一个成员会影响其他成员
{
*/
union DataU
{
	int i;		//4个字节
	double d;	//8个字节
	char s[10];	//10个字节
	//联合体成员大小由最大的成员决定,因此该联合体的大小是10个字节
};
/*
1、定义和使用分开
union DataU
{
	int i;		//4个字节
	double d;	//8个字节
	char s[10];	//10个字节
	//联合体成员大小由最大的成员决定,因此该联合体的大小是10个字节
};
DataU a,b,c;
2、定义和使用结合
union DataU
{
	int i;		
	double d;	
	char s[10];	
}a,b,c;
3、匿名:不想让别人使用
union
{
	int i;
	double d;
	char s[10];
}a,b,c;
*/
int main()
{
	DataS ds;
	cout << &ds.i << "," << &ds.d << "," << (void*)ds.s << endl;

	DataU du;
	cout << &du.i << "," << &du.d << "," << (void*)du.s << endl;
	return 0;
}

2 联合体的内存布局

cpp 复制代码
#include <iostream>
using namespace std;

union DataU {
    int i;      // 4
    double d;   // 8
    char s[7];  // 7
};

int main() {
    cout << sizeof(DataU) << endl;
    DataU du;
    du.s[0] = 255;      // 11111111
    du.s[1] = 1;        // 00000001
    du.s[2] = 0;        // 00000000
    du.s[3] = 0;        // 00000000
    cout << du.i << endl; // 00000000 00000000 00000001 11111111
    du.i = 256;
    cout << (int)du.s[0] << (int)du.s[1] << (int)du.s[2] << (int)du.s[3] << endl;

    return 0;
}

3 联合体的应用

cpp 复制代码
#include <iostream>

using namespace std;

struct Info
{
	char _name[20];
	int _role;
	union 
	{
		double score;
		char course[20];
	}_sc;

	Info(const char name[20], int role, double s, const char c[20]) {
		strcpy_s(_name, name);
		_role = role;
		if (s > 0) _sc.score = s;
		if (strlen(c) > 0) strcpy_s(_sc.course, c);
	}
};

int main()
{
	Info a[4] = {
		Info("周老师", 0, -1, "CGaGa"),
		Info("周老师", 0, -1, "Python"),
		Info("周同学", 1, 90, ""),
		Info("肖同学", 1, 88, ""),
	};

	for (int i = 0; i < 4; i++)
	{
		if (a[i]._role == 0) {
			cout << a[i]._name << "是一位老师,他是教" << a[i]._sc.course << endl;
		}
		else if (a[i]._role == 1) {
			cout << a[i]._name << "是一位学生,他的分数是" << a[i]._sc.score << endl;
		}
	}
	return 0;
}
相关推荐
骁的小小站3 分钟前
HDLBits刷题笔记和一些拓展知识(十一)
开发语言·经验分享·笔记·其他·fpga开发
Jtti5 分钟前
如何准确查看服务器网络的利用率?
开发语言·php
人生在勤,不索何获-白大侠10 分钟前
day17——Java集合进阶(Collections、Map)
java·开发语言
程序员小羊!22 分钟前
Java教程:JavaWeb ---MySQL高级
java·开发语言·mysql
m0_7231402329 分钟前
Python训练营-Day49
开发语言·python
一洽客服系统1 小时前
网页嵌入与接入功能说明
开发语言·前端·javascript
mit6.8241 小时前
[Meetily后端框架] Whisper转录服务器 | 后端服务管理脚本
c++·人工智能·后端·python
zhangfeng11331 小时前
python 数据分析 单细胞测序数据分析 相关的图表,常见于肿瘤免疫微环境、细胞亚群功能研究 ,各图表类型及逻辑关系如下
开发语言·python·数据分析·医学
Sylvia-girl2 小时前
Java---IDEA
java·开发语言·intellij-idea
Z_W_H_2 小时前
【Springboot】Bean解释
java·开发语言