• C++ 结构与联合


    1.结构体的两种定义方法和变量的三种声明方法:

    #include <iostream>
    using namespace std;
    
    /* 结构体的两种定义方式 */
    struct test01{
        int a;
        double b;
        float c;
    };
    
    typedef struct {
        int a ;
        double b;
        float c;
    } test02;
    
    int main(int argc, char* argv[]){
        /* 结构体变量的三种声明方式 */
        struct test01 t;    /* 需要struct标签 */
        test02 t1;          /* 不需要标签 */
    
        struct {
            int a;
            double b;
            float c;
        } t2;
        return 0;
    }

    2.结构体成员的访问

    #include <iostream>
    
    using namespace std;
    
    typedef struct {
        int a;
        double b[10];
        float c;
    }test_t;
    
    
    int main(int argc, char* argv[]){
    
        test_t t;
        t.a = 1;     /* 结构体使用.访问成员 */
    
        test_t *t1;
        t1->a = 1;   /* 对于指针类型的结构体使用->访问成员 */
        (*t1).a =1;  /* *运算符优先级低于.,所以需要加括号 */
    
        return 0;
    }

    3.结构体的自引用

    #include <iostream>
    
    // struct test_t{
    //     int a;
    //     double b[10];
    //     float c;
    //     struct test_t t;       /* 在结构体中自己的变量是不合法的,因为这个操作会引起无穷的递归 */
    // };
    
    struct test_t
    {
        int a;
        double b[10];
        float c;
        struct test_t *t; /* 此处是合法的,因为t只是一个指针,不会引起无穷递归 */
    };
    
    typedef struct
    {
        int a;
        double b[10];
        float c;
        test01_t *t; /* 这是一个陷阱, 编译器解释到这一行时,test01_t还没有被定义 */
    } test01_t;
    
    /* 正确的做法如下 */
    typedef struct test02_tag
    {
        int a;
        double b[10];
        float c;
        struct test02_tag *t;
    } test02_t;

    4.结构体的交叉引用,不完整声明

    #include <iostream>
    
    using namespace std;
    
    /* 如果存在两个结构体 A 和 B,它们相互引用,应该如何定义呢? 或者说先定义谁呢?*/
    struct B;  /* 不完整定义 */
    
    struct A
    {
        int a;
        double b[10];
        float c;
        struct B *b;
    };
    
    struct B
    {
        struct A *a;
    };
    
    int main(int argc, char *argv[])
    {
    
        return 0;
    }
  • 相关阅读:
    LNMP笔记:解决mail函数不能发送邮件
    OPENCART记录账户密码
    Nginx 0.8.5版本access.log日志分析shell命令
    几个查询信息的api接口
    chart 图表无法在显示
    RegularExpressionValidator
    用户 'WANGYACONG\ASPNET' 登录失败
    'IIS APPPOOL\ASP.NET V4.0' 登录失败
    正则表达式(转载)
    不小心删除了默认数据库的恢复方法
  • 原文地址:https://www.cnblogs.com/PPWEI/p/11430631.html
Copyright © 2020-2023  润新知