zoukankan      html  css  js  c++  java
  • C语言基础:C语言结构体(7)

    上一节, 我们讲解了结构体与函数, 这次我们来讲解一下结构体的嵌套使用.


    比如有一个学生, 我需要知道他的学号, 生日年月日, 入学年月日, 如果用结构体我们需要怎么做呢?


    按照常规的定义, 就像下面的例子:

    #include <stdio.h>
    
    int main()
    {
        struct Date
        {
            int number; //学号
            
            int year;   //生日
            int month;
            int day;
            
            int year2;  //入学
            int month2;
            int day2;
        };
        
        return 0;
    }

    这样子我们才能完整的实现我们的需求, 但如果我还需要多个数据呢? 那不就要定义更多的成员变量了吗? 为了实现这个要求, 我们还有另外一种方式, 就像下面的例子:

    #include <stdio.h>
    
    int main()
    {
        struct Date
        {
            int year;
            int month;
            int day;
        };
        
        struct Student
        {
            int number; //学号
            
            struct Date birthday;   //生日
            struct Date startSchool;    //入学时间
        };
        
        struct Student stu = {1, {1999, 12, 20}, {2005, 9, 1}};
        
        printf("year = %d   month = %d  day = %d
    ", stu.birthday.year, stu.birthday.month, stu.birthday.day);
        
        return 0;
    }

    结构体的嵌套使用, 可以更加的方便我们去调用和实现需求~~但有一个注意点, 结构体嵌套是不能包含它自己本身, 就好像下面这个错误的例子:

    #include <stdio.h>
    
    int main()
    {
        struct Date
        {
            int year;
            int month;
            int day;
        };
        
        struct Student
        {
            int number; //学号
            
            struct Date birthday;   //生日
            struct Date startSchool;    //入学时间
            
            struct Student stu;
        };
    
        return 0;
    }

    这是错误的写法, 编译器是不会允许通过的.



    结构体讲到这里, 就已经讲完了, 其实除了结构体还有一种类型叫做共用体, 也叫做联合体, 一般来讲开发基本上是用不到, 所以这里不特别的说明, 有兴趣的童鞋们可以自行百度一下~~顺便练练自己的自学能力~~~下次我们再见~

  • 相关阅读:
    Wamp 访问本地站点慢 的解决办法
    PHP中如何实现 “在页面中一边执行一边输出” 的效果
    PHP很有用的一个函数ignore_user_abort ()
    PHP中CURL方法curl_setopt()函数的一些参数
    RGB转为Lab空间
    void v.s. void *
    __attribute__((regparm(3))) from GNU C
    a number of 和the number of用法
    Linux 版本查詢
    在frameset,iframe內調用Javascript的方法
  • 原文地址:https://www.cnblogs.com/iOSCain/p/4282880.html
Copyright © 2011-2022 走看看