weixin_43240986 2019-07-07 15:17 采纳率: 0%
浏览 1665

c++里的结构体还有必要用typedef吗?

c语言里声明了结构体后,在定义结构体变量时,要如下形式:

struct A { // 声明结构体A
    int a;
};

struct A a_st; // 定义结构体
struct A *a_p; // 定义结构体指针

为了方便使用,c里面通常用typedef来声明结构体:

typedef struct _A{ // 用typedef声明结构体
    int a;
} A, *PA;

A a_st; //定义结构体
PA a_p; //定义结构体指针

但是在c++中,结构体的在定义的时候,struct关键字是不必要的

struct A { // 声明结构体
    int a;
};

A a_st;  //定义结构体
A* a_p; // 定义结构体指针

我的问题是,在c++中,还有必要使用typedef的方式来声明结构体吗?

  • 写回答

4条回答 默认 最新

  • Walter0511 2019-07-07 19:06
    关注

    C++代码中定义几个结构体,我们可能会看到这样的代码:

    typedef struct student
    {
    string name;
    int age;
    string gender;
    }student;

    为什么struct关键字后面有结构体名称student了,还需要用typedef再重新给定一个名字呢?
    这是因为如果不使用typedef,即

    struct student
    {
    string name;
    int age;
    string gender;
    };

    在C语言中使用的时候,必须这样定义一个变量:
    struct student stu1 = {"TheOne", 24, "male"};

    所以在C语言中会使用typedef将struct student定义为student,这样我们使用student结构体的时候可以省略struct,即:

    student stu1 = {"TheOne", 24, "male"};

    但是在C++中,一切都变得简单了,我们不需要使用typedef,也可以直接使用student定义变量。即:

    结构体:

    struct student
    {
    string name;
    int age;
    string gender;
    };
    变量定义:
    student stu1 = {"TheOne", 24, "male"};

    所以说C++中看到的typedef只是为了兼容C的写法。

    作者:TheOneGIS
    来源:CSDN
    原文:https://blog.csdn.net/theonegis/article/details/40049667
    版权声明:本文为博主原创文章,转载请附上博文链接!

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧