匿名结构体与匿名联合体

C 语言中的匿名联合体和匿名结构

* 重点是:C++联合体中不能包含非基本类型成员变量,原因好像是因为非基本类型存在构造函数(包括默认构造函数)为了避免多层嵌套后结构的安全性*

在 C 语言中,可以在结构体中声明某个联合体(或结构体)而不用指出它的名字,如此之后就可以像使用结构体成员一样直接使用其中联合体(或结构体)的成员。

下面是一段摘录自 msdn 对 anonymous structures 的解释

A Microsoft C extension allows you to declare a structure variable within another structure without giving it a name.

These nested structures are called anonymous structures. C++ does not allow anonymous structures.

You can access the members of an anonymous structure as if they were members in the containing structure.

#include <stdio.h>    

struct person    
{    
    char    *name;    
    char     gender;    
    int      age;    
    int      weight;    
    struct  
    {    
        int  area_code;    
        long phone_number;    
    };   
};    

int main(void)    
{  
    struct person jim = {"jim", 'F', 28, 65, {21, 58545566}};  
    printf("%d\n", jim.area_code);       
}   

如果不使用匿名结构体,则上述例子对应的代码如下:

#include <stdio.h>    

struct phone  
{  
    int  area_code;  
    long phone_number;  
};  

struct person    
{    
    char        *name;    
    char         gender;    
    int          age;    
    int          weight;    
    struct phone office;  
};    

int main(void)    
{  
    struct person jim = {"jim", 'F', 28, 65, {21, 58545566}};  

    printf("%d\n", jim.office.area_code);       
}   

对比上述两个例子可以看出:

使用匿名结构体,结构体对象 jim 可以通过 jim.area_code 直接访问匿名结构体成员变量 area_code,代码相对比较简洁

反之则必须通过 jim.office.area_code 来访问结构体成员变量

匿名联合体举例如下:

#include <stdio.h>  

struct person  
{  
    char    *name;  
    union  
    {  
        char gender;  
        int  id;  
    };  
    int      age;  
};  

int main(void)  
{  
    struct person jim = {"jim", 'F', 28};  

    printf("jim.gender = %c, jim.id = %d\n", jim.gender, jim.id);  

    return 0;  
} 

如果不适用匿名联合体,那么程序如下:

#include <stdio.h>  

union u  
{  
    char gender;  
    int  id;  
};  

struct person  
{  
    char   *name;  
    union u test;   
    int     age;  
};  

int main(void)  
{  
    struct person jim = {"jim", 'F', 28};  

    printf("jim.test.gender = %c, jim.test.id = %d\n", jim.test.gender, jim.test.id);  

    return 0;  
}  
  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值