struct和typedef struct的区别
一.前言
typedef 和宏定义#define 的区别:
- typedef是为一个类型起新的名字,而#define则只是简单的字符串替换,举例:
typedef char* pStr1;
#define pStr2 char*;
pStr1 s1,s2;
pStr2 s3,s4;
在上述的变量定义中,s1,s2,s3都被定义为char*,而s4则被定义为char.
上列中define语句必须写成pStr s3, *s4;这样才能正常执行。
#define与typedef优缺点比较
1).#define宏定义长处:可以使用#ifdef,#ifndef等来进行逻辑判断,还可以使用#undef来取消定义。
2).typedef长处:它符合作用域范围规则,使用typedef定义的变量类型其作用域限制在其所定义的函数或者文件内(取决于此变量定义的位置),而宏定义则没有这种特性。
typedef & 复杂的变量声明
理解复杂声明可用的“右左法则”:
从变量名看起,先往右,再往左,碰到一个圆括号就调转阅读的方向;括号内分析完就跳出括号,还是按先右后左的顺序,如此循环,直到整个声明分析完。举例:
int (*func)(int *p);
首先找到变量名func,外面有一对圆括号,而且左边是一个号,这说明func是一个指针;然后跳出这个圆括号,先看右边,又遇到圆括号,这说明 (*func)是一个函数,所以func是一个指向这类函数的指针,即函数指针,这类函数具有int类型的形参,返回值类型是int。
二.typedef综述
typedef为一个类型定义起新的别名。
typedef struct tagMyStruct
{
int a;
}Stu;//不规范的写法
//规范写法如下
typedef struct tagMyStruct
{
int a;
};
typedef struct Stu;
上面的tagMyStruct是标识符,MyStruct是变量类型(相当于(int,char等))。
在C中,这个声明后申请结构变量的方法有两种:
(1)struct Student 变量名
(2)stu 变量名
在C++中有三种:
(1)struct tagMyStruct 变量名
(2)stu 变量名
(3)tagMyStruct 变量名
三.在C和C++中的不同
- 在C中定义一个结构体类型要用typedef:
typedef struct Student
{
int a;
}Stu;
于是在声明变量时就可以用:Stu stu1;
这里的Stu实际上就是struct Student的别名。Stu==struct Student。
如果没有typedef就必须用struct Stu stu1;来声明。
另外这里也可以不写Student(于是也不能struct Student stu1;了,必须是 Stu stu1;
2.在C++里直接
struct Student
{
int a;
};
于是就定义了结构体类型Student,声明变量是直接Student stu2;。
3.在C++中用typedef
struct Student
{
int a;
}stu1;//stu1是一个变量
typedef struct Student2
{
int a;
}stu2;//stu2是一个结构体类型=struct Student
使用时可以直接访问stu1.a,但是stu2则必须先 stu2 s2; 然后s2.a=10;