匿名结构(C11)

作者:追风剑情 发布于:2020-3-11 10:00 分类:C

示例

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdbool.h>
  4.  
  5. struct names
  6. {
  7. char first[20];
  8. char last[20];
  9. };
  10. struct person
  11. {
  12. int id;
  13. struct names name; //嵌套结构成员
  14. };
  15. //初始化嵌套结构
  16. struct person ted = { 8483, {"Ted", "Grass"} };
  17.  
  18. //在C11中,可以用嵌套的匿名成员结构定义person;
  19. struct person1
  20. {
  21. int id;
  22. struct { char first[20]; char last[20]; }; //匿名结构
  23. //PS: 匿名特性在嵌套联合中更加有用
  24. };
  25. //初始化嵌套结构
  26. struct person1 ted1 = { 8483, {"Ted", "Grass"} };
  27.  
  28. int main(int argc, char* argv[])
  29. {
  30. //访问嵌套结构
  31. puts(ted.name.first);
  32.  
  33. //访问匿名结构
  34. puts(ted1.first);
  35.  
  36. system("pause");
  37. return 0;
  38. }

运行测试

1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号