先前看了SDL的SDL_Event, 不大明白其中的用法,后来翻了翻书中关于union的用法,再则看到了云风的这篇文章C 语言中统一的函数指针, 就写了一个不成文的例子, 把union作为函数的参数传递, 可以将两个毫不相干的不同类型的结构数据粘合在一起, 的确很有意思.
#include <stdio.h>
#include <stdlib.h>
typedef enum bool {false, true} bool;
typedef struct Number {
unsigned char type;
unsigned int num;
bool sign;
} Number;
typedef struct OP {
unsigned char type;
char ch;
} OP;
typedef union Button {
unsigned char type;
Number num;
OP op;
} Button;
void printNum(int num)
{
printf("Print Number:%d\n", num);
}
void printOP(char op)
{
printf("Print Op:%c\n", op);
}
void cal(Button p)
{
switch(p.type)
{
case 1:
printNum(p.num.num * ((p.num.sign) ? 1 : -1));
break;
case 2:
printOP(p.op.ch);
break;
}
}
int main()
{
Button p1;
p1.num = (Number) {1, 9, false};
cal(p1);
p1.op = (OP) {2, '='};
cal(p1);
exit(0);
}
这里要注意结构体的第一个字段一定要与union的第一个字符对应起来, 至于为什么, 去翻看union用法吧...