zoukankan      html  css  js  c++  java
  • c中结构体的4种定义

    1、常规的标准方式:

     1 #include <stdio.h>
     2 
     3 struct student{
     4     int age;
     5     float score;
     6     char sex;
     7 };
     8 
     9 int main(int argc, char **argv)
    10 {
    11     struct student studenta = {
    12         30,
    13         79.5,
    14         'm'
    15     };
    16 
    17     printf("年龄: %d, 分数: %.2f  性别:%c ", studenta.age, studenta.score, studenta.sex);
    18 
    19     return 0;
    20 }

    编译::!gcc % -o %<

    运行::!%<

    结果:年龄: 30, 分数: 79.50  性别:m


    2、不够标准的方式(声明时初始化):

     1 #include <stdio.h>
     2 
     3 struct student{
     4     int age;
     5     float score;
     6     char sex;
     7 } studenta = {
     8     30,
     9     79.5,
    10     'm'
    11 };
    12 
    13 int main(int argc, char **argv)
    14 {
    15     printf("年龄: %d, 分数: %.2f  性别:%c ", studenta.age, studenta.score, studenta.sex);
    16 
    17     return 0;
    18 }

    编译::!gcc % -o %<

    运行::!%<

    结果:年龄: 30, 分数: 79.50  性别:m


    3、最糟糕的方式(不完全声明时初始化):

     1 #include <stdio.h>
     2 
     3 struct {
     4     int age;
     5     float score;
     6     char sex;
     7 } studenta = {
     8     30,
     9     79.5,
    10     'm'
    11 };
    12 
    13 int main(int argc, char **argv)
    14 {
    15     printf("年龄: %d, 分数: %.2f  性别:%c ", studenta.age, studenta.score, studenta.sex);
    16 
    17     return 0;
    18 }

    编译::!gcc % -o %<

    运行::!%<

    结果:年龄: 30, 分数: 79.50  性别:m


    4、我推崇的方式:

     1 #include <stdio.h>
     2 
     3 typedef struct _student{
     4     int age;
     5     float score;
     6     char sex;
     7 } Student;
     8 
     9 int main(int argc, char **argv)
    10 {
    11     Student studenta = {
    12         30,
    13         79.5,
    14         'm'
    15     };
    16 
    17     printf("年龄: %d, 分数: %.2f  性别:%c ", studenta.age, studenta.score, studenta.sex);
    18 
    19     return 0;
    20 }

    编译::!gcc % -o %<

    运行::!%<

    结果:年龄: 30, 分数: 79.50  性别:m


    这几种方式中,第四种的优点:

    1.使用了类型定义,typedef

    2.遵照了结构体的命名约定,就是在student前加_,使用_student

    3.使用首字母大写式的命名,使得使用者明白这是一种类型,而不是普通变量

    4.为将来的使用创建了良好的基础,后期声明无需频繁使用struct表明是结构体,只需要使用Student即可,既便于使用和理解,又能有效的完成封装与信息隐藏。


    因此,个人更推崇第四种方式。

    读人民邮电出版社的《深入理解C指针》原著:Richard Reese 陈晓亮译,p126有感,于九江学院通信实训中心机房 2015年 3月30日

  • 相关阅读:
    vs2013常用快捷键收集
    关于cocos2d-x 与 cocos2d-html5 资源预加载的思考
    【转】使用cocos2d-console工具转换脚本为字节码
    多层CCLayer的touch冲突解决
    jsb里出现的 Invalid Native Object的一次bug修复的思考
    win7 通过命令行压缩文件
    消格子时一个很深的bug的修复纪录
    mac自带apache服务器开启
    shell命令:给当前目录里一个文件压缩一份不包含.svn文件的zip包
    shell命令:删除当前.sh文件所在目录下的zip包,并且重新打包
  • 原文地址:https://www.cnblogs.com/guochaoxxl/p/6823195.html
Copyright © 2011-2022 走看看