union与struct的区别

共用体中所有成员公用一块地址空间

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

#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);
	
}

以下是参考文章

点击打开链接


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值