结构的数据成员可以是任何类型,包括联合(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