结构化
#include <iostream>
int main()
{
struct contact {
char phone[20];
char email[20];
};
struct person {
char name[20];
int gender;
double h;
double w;
struct contact c;
};
struct person timmy = {
"timmy", 1, 170.00, 60.00,
{"13012345678", "timmy@xxx.com"}
};
std::cout << timmy.name << std::endl;
std::cout << timmy.gender << std::endl;
std::cout << timmy.h << std::endl;
std::cout << timmy.w << std::endl;
std::cout << timmy.c.phone << std::endl;
std::cout << timmy.c.email << std::endl;
struct person *p = &timmy;
std::cout << p->name << std::endl;
std::cout << (*p).name << std::endl;
std::cout << (*p).c.email << std::endl;
return 0;
}
联合与枚举
#include <iostream>
enum msgType {
eInteger = 1,
eIFloat = 3,
eString = 5,
};
struct message {
enum msgType type;
union {
int n;
float f;
char str;
}u;
};
void printMsg(struct message msg)
{
switch (msg.type)
{
case eInteger:
std::cout << msg.u.n << std::endl;
break;
case eIFloat:
std::cout << msg.u.f << std::endl;
break;
case eString:
std::cout << msg.u.str << std::endl;
break;
}
}
int main()
{
struct message msg[3];
msg[0].type = eInteger;
msg[0].u.n = 123;
msg[1].type = eIFloat;
msg[1].u.f = 3.14;
msg[2].type = eString;
msg[2].u.str = 'A';
for (int i=0; i < 3; i++) {
printMsg(msg[i]);
}
return 0;
}