您的位置:首页 > 其它

union与struct的区别

2014-12-26 00:25 274 查看
共用体中所有成员公用一块地址空间

结构体中所有成员都有单独的一块地址空间,下面的例子是公用函数指针

#include <stdlib.h>
#include <stdio.h>
typedef void   (*FUNC  )(void);
typedef void   (*Func01)(int, int);
typedef double (*Func02)(double, double);
typedef int    (*Func03)(int, int);

void   Test01(int, int);
double Test02(double, double);
int    Test03(int, int);

union UnionTest
{
FUNC pFunc;
Func01 func01;
Func02 func02;
Func03 func03;
};

int main(int argc, char* argv[])
{
system("cls");
printf("此程序模仿了MFC中的消息函数分配机制\n");
union UnionTest test;

test.pFunc = (FUNC)(static_cast< void (*)(int, int) > (Test01));
printf("%p, %p, %p\n", test.func01, test.func02, test.func03);
test.func01(10,10);
test.func02(10.111, 20.222);
test.func03(10,10);
printf("\n");

test.pFunc = (FUNC)(static_cast< double (*)(double, double) > (Test02));
printf("%p, %p, %p\n", test.func01, test.func02, test.func03);
test.func01(10,10);
test.func02(10.111, 20.222);
test.func03(10,10);
printf("\n");

test.pFunc = (FUNC)(static_cast< int (*)(int, int) > (Test03));
printf("%p, %p, %p\n", test.func01, test.func02, test.func03);
test.func01(10,10);
test.func02(10.111, 20.222);
test.func03(10,10);
printf("\n");

return 0;
}

void Test01(int x, int y)
{
printf("Test01\t:\n");
}

double Test02(double x, double y)
{
printf("Test02\t: \n");
return 0;
}

int Test03(int x, int y)
{
int sum =x+y;
printf("Test03\t:\n");
return 0;
}
以下是程序的输出结果:



下面的例子是公用非函数指针的类型

#include <stdio.h>

union
{
int i;
struct
{
char first;
char second;
char third;
char fourth;
}half;
}number;

void main()
{
number.i = 0x87654321;

// 87654321
// 214365ffffff87
printf("%x\n", number.i);
printf("%x%x%x%x\n", number.half.first, number.half.second, number.half.third, number.half.fourth);

number.half.first = 1;
number.half.second = 2;
number.half.third = 4;
number.half.fourth = 8;

// 80402010
// 1248
printf("%x\n", number.i);
printf("%x%x%x%x\n", number.half.first, number.half.second, number.half.third, number.half.fourth);

}

以下是参考文章

点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: