typedef struct和struct比较

//相当于为现有类型创建一个别名,或称类型别名。
//整形等
typedef int size;


//字符数组
char line[81];
char text[81];//=>

typedef char Line[81];
Line text, secondline;


//指针
typedef char * pstr;
int mystrcmp(pstr p1, pstr p2);//注:不能写成int mystrcmp(const pstr p1, const pstr p3);因const pstr p1解释为char * const cp(不是简单的替代)


//与结构类型组合使用
typedef struct tagMyStruct
{
int iNum;
long lLength;
} MyStruct;//(此处MyStruct为结构类型别名)=>

struct tagMyStruct
{
int iNum;
long lLength;
};//+
typedef struct tagMyStruct MyStruct;


//结构中包含指向自己的指针用法
typedef struct tagNode
{
char *pItem;
pNode pNext;
} *pNode;//=>error
//1)
typedef struct tagNode
{
char *pItem;
struct tagNode *pNext;
} *pNode;
//2)
typedef struct tagNode *pNode;
struct tagNode
{
char *pItem;
pNode pNext;
};
//3)规范
struct tagNode
{
char *pItem;
struct tagNode *pNext;
};
typedef struct tagNode *pNode;


//与define的区别
//1)
typedef char* pStr1;//重新创建名字
#define pStr2 char *//简单文本替换
pStr1 s1, s2;
pStr2 s3, s4;=>pStr2 s3, *s4;
//2)define定义时若定义中有表达式,加括号;typedef则无需。
#define f(x) x*x=>#define f(x) ((x)*(x))
main( )
{
int a=6,b=2,c;
c=f(a) / f(b);
printf("%d \\n",c);
}
//3)typedef不是简单的文本替换
typedef char * pStr;
char string[4] = "abc";
const char *p1 = string;
const pStr p2 = string;=>error
p1++;
p2++;

//1) #define宏定义有一个特别的长处:可以使用 #ifdef ,#ifndef等来进行逻辑判断,还可以使用#undef来取消定义。
//2) typedef也有一个特别的长处:它符合范围规则,使用typedef定义的变量类型其作用范围限制在所定义的函数或者文件内(取决于此变量定义的位置),而宏定义则没有这种特性。

第二种:

//
//C中定义结构类型
typedef struct Student
{
int a;
}Stu;//申明变量Stu stu1;或struct Student stu1;
//或
typedef struct
{
int a;
}Stu;//申明变量Stu stu1;

//C++中定义结构类型
struct Student
{
int a;
};//申明变量Student stu2;


//C++中使用区别
struct Student
{
int a;
}stu1;//stu1是一个变量 。访问stu1.a

typedef struct Student2
{
int a;
}stu2;//stu2是一个结构体类型 访问stu2 s2; s2.a=10;
//还有待增加。

猜你喜欢

转载自www.cnblogs.com/0505-cheng/p/9500823.html