C++ 结构与联合

本文详细介绍了C++中结构体的定义与使用,包括结构体的两种定义方法、变量的三种声明方法,结构体成员的访问,结构体的自引用与交叉引用,以及不完整声明的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

转载于:https://www.cnblogs.com/PPWEI/p/11430631.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值