結構的數據成員可以是任何類型,包括聯合(union)和其他結構。
聲明一個復雜點的結構,它有兩個成員,第一個成員是一個聯合,第二個成員是枚舉。
enum Type {Double, Float, Long, Int};
stuct SharedData {
union {
double dData;
float fData;
long lData;
int iData;
};
Type type;
};
注意,SharedData的聯合成員是匿名的,這表示在引用SharedData類型的對象的聯合成員時,不必指定聯合名。
練習題:
擴展上面的SharedData結構及相關的枚舉類型,以存儲4種類型的指針。測試一下,看看是否能存儲變量的指針。
參考答案:

shareddata.h
// shareddata.h
// Definitions for Type enumeration and SharedData structure
#ifndef SHAREDDATA_H
#define SHAREDDATA_H
enum Type { Double, Float, Long, Int, pDouble, pFloat, pLong, pInt };
struct SharedData {
union { // An anonymous union
double dData;
float fData;
long lData;
int iData;
double* pdData; // Pointers to various types
float* pfData;
long* plData;
int* piData;
};
Type type; // Variable of the enumeration type Type
void show(); // Display a SharedData value
};
#endif

shareddata.cpp
// shareddata.cpp
// SharedData function definition
#include "shareddata.h"
#include <iostream>
using std::cout;
using std::endl;
void SharedData::show() {
switch (type) {
case Double:
cout << endl << "Double value is " << dData << endl;
break;
case Float:
cout << endl << "Float value is " << fData << endl;
break;
case Long:
cout << endl << "Long value is " << lData << endl;
break;
case Int:
cout << endl << "Int value is " << iData << endl;
break;
case pDouble:
cout << endl << "Pointer to double value is " << *pdData << endl;
break;
case pFloat:
cout << endl << "Pointer to float value is " << *pfData << endl;
break;
case pLong:
cout << endl << "Pointer to long value is " << *plData << endl;
break;
case pInt:
cout << endl << "Pointer to int value is " << *piData << endl;
break;
default:
cout << endl << "Error - Invalid Type" << endl;
break;
}
};

main.cpp
// main.cpp
// Exercisiong SharedData
#include "shareddata.h"
#include <iostream>
using std::cout;
using std::endl;
void main() {
int number = 99;
long lNumber = 9999999L;
double value = 1.618;
float pi = 3.1415f;
SharedData shared = { 0.1 }; // Initially a double
shared.show();
// Now try all four pointers
shared.piData = &number;
shared.type = pInt;
shared.show();
shared.plData = &lNumber;
shared.type = pLong;
shared.show();
shared.pdData = &value;
shared.type = pDouble;
shared.show();
shared.pfData = π
shared.type = pFloat;
shared.show();
}
輸出結果:
Double value is 0.1
Pointer to int value is 99
Pointer to long value is 9999999
Pointer to double value is 1.618
Pointer to float value is 3.1415