北京的網(wǎng)站建設(shè)公司廣州白云區(qū)最新信息
目錄
1 聯(lián)合體的定義和使用
2 聯(lián)合體的內(nèi)存布局?
3 聯(lián)合體的應(yīng)用
1 聯(lián)合體的定義和使用
#include <iostream>using namespace std;struct DataS
{int i; double d; char s[10]; };/*聯(lián)合體 所有成員共享同一段內(nèi)存 修改一個(gè)成員會(huì)影響其他成員
{
*/
union DataU
{int i; //4個(gè)字節(jié)double d; //8個(gè)字節(jié)char s[10]; //10個(gè)字節(jié)//聯(lián)合體成員大小由最大的成員決定,因此該聯(lián)合體的大小是10個(gè)字節(jié)
};
/*
1、定義和使用分開
union DataU
{int i; //4個(gè)字節(jié)double d; //8個(gè)字節(jié)char s[10]; //10個(gè)字節(jié)//聯(lián)合體成員大小由最大的成員決定,因此該聯(lián)合體的大小是10個(gè)字節(jié)
};
DataU a,b,c;
2、定義和使用結(jié)合
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 聯(lián)合體的內(nèi)存布局?
#include <iostream>
using namespace std;union DataU {int i; // 4double d; // 8char s[7]; // 7
};int main() {cout << sizeof(DataU) << endl;DataU du;du.s[0] = 255; // 11111111du.s[1] = 1; // 00000001du.s[2] = 0; // 00000000du.s[3] = 0; // 00000000cout << du.i << endl; // 00000000 00000000 00000001 11111111du.i = 256;cout << (int)du.s[0] << (int)du.s[1] << (int)du.s[2] << (int)du.s[3] << endl;return 0;
}
3 聯(lián)合體的應(yīng)用
#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("周同學(xué)", 1, 90, ""),Info("肖同學(xué)", 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 << "是一位學(xué)生,他的分?jǐn)?shù)是" << a[i]._sc.score << endl;}}return 0;
}