C++编程思想 第1卷 第3章 创建复合类型 用union节省内存

有时程序会使用同一个变量
同一个变量来处理不同的数据类型
创建一个struct,存储所有可能不同的类型
或者使用union 联合
联合把所有的数据放在一个单独的空间
计算union的最大项所需的空间 生成union的大小
使用union可以节省内存
union中存放一个值,这个值总放在union开始的同一个地方
这个地方只使用必要的空间
创建一个能容纳任何一个变量的超变量

所有的union变量的地址是一样的


//: C03:Union.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// The size and simple use of a union
#include <iostream>
using namespace std;

union Packed { // Declaration similar to a class
  char i;
  short j;
  int k;
  long l;
  float f;
  double d;  
  // The union will be the size of a 
  // double, since that's the largest element
};  // Semicolon ends a union, like a struct

int main() {
  cout << "sizeof(Packed) = " 
       << sizeof(Packed) << endl;
  Packed x;
  x.i = 'c';
  cout << x.i << endl;
  x.d = 3.14159;
  cout << x.d << endl;
  getchar();
} ///:~

C++编程思想


猜你喜欢

转载自blog.csdn.net/eyetired/article/details/80720080
今日推荐