This commit is contained in:
Light-City
2019-11-05 16:56:07 +08:00
parent 3a495d7fa2
commit 8edbbbc5a2
179 changed files with 428 additions and 26 deletions

View File

@@ -0,0 +1,18 @@
# UNION那些事
## 关于作者:
个人公众号:
![](../img/wechat.jpg)
联合union是一种节省空间的特殊的类一个 union 可以有多个数据成员,但是在任意时刻只有一个数据成员可以有值。当某个成员被赋值后其他成员变为未定义状态。联合有如下特点:
- 默认访问控制符为 public
- 可以含有构造函数、析构函数
- 不能含有引用类型的成员
- 不能继承自其他类,不能作为基类
- 不能含有虚函数
- 匿名 union 在定义所在作用域可直接访问 union 成员
- 匿名 union 不能包含 protected 成员或 private 成员
- 全局匿名联合必须是静态static

BIN
basic_content/union/union Executable file

Binary file not shown.

View File

@@ -0,0 +1,50 @@
/**
* @file union.cpp
* @brief UNION
* @author 光城
* @version v1
* @date 2019-08-06
*/
#include<iostream>
/**
* 默认访问控制符为public
*/
union UnionTest {
/**
* 可以含有构造函数、析构函数
*/
UnionTest() : i(10) {print(i);};
~UnionTest(){};
int i;
private:
void print(int i){std::cout<<i<<std::endl;};
};
/**
* 全局匿名联合必须是静态的
*/
static union {
int i;
double d;
};
int main() {
UnionTest u;
union {
int i;
double d;
};
std::cout << u.i << std::endl; // 输出 UnionTest 联合的 10
::i = 20;
std::cout << ::i << std::endl; // 输出全局静态匿名联合的 20
/**
* 匿名union在定义所在作用域可直接访问union成员
*/
i = 30;
std::cout << i << std::endl; // 输出局部匿名联合的 30
return 0;
}