C++编程思想 第1卷 第7章 函数重载与默认参数 联合

C++中,struct和class的不同之处,struct默认为public,class为private
也可以让struct有构造函数和析构函数
union可以有构造函数,析构函数,成员函数甚至访问控制

//: C07:UnionClass.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Unions with constructors and member functions
#include<iostream>
using namespace std;

union U {
private: // Access control too!
  int i;
  float f;
public:  
  U(int a);
  U(float b);
  ~U();
  int read_int();
  float read_float();
};

U::U(int a) { i = a; }

U::U(float b) { f = b;}

U::~U() { cout << "U::~U()\n"; }

int U::read_int() { return i; }

float U::read_float() { return f; }

int main() {
  U X(12), Y(1.9F);
  cout << X.read_int() << endl;
  cout << Y.read_float() << endl;
  getchar();
} ///:~

union与class 不同之处在于存储数据的方式
union不能再基础作为基类使用


输出
12
1.9

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81142051