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的方式来声明结构体吗?
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"};
作者:TheOneGIS
来源:CSDN
原文:https://blog.csdn.net/theonegis/article/details/40049667
版权声明:本文为博主原创文章,转载请附上博文链接!
没有必要,如你所说的那样。C++不需要变量定义的时候加上struct,所以没必要typedef了。
C++中的struct其实和class意义一样,唯一不同就是struct里面默认的访问控制是public,class中默认的访问控制是private。C++中存在struct关键字的意义就是为了让C程序员有归属感,让C++编译器兼容以前用C开发的项目。
如果打算移植到c(比如装了个只支持c的系统),那么tyoedef就挺有必要的,但如果不移植,那么没必要,浪费时间