C++/C之struct和typedef struct

struct和typedef struct

在C裏

typedef struct Student
{
	int a;
}Stu;

於是在聲明變量的時候就可:

Stu stu1;

這裏的Stu實際上就是struct Student的別名。
Stu==struct Student
另外這裏也可以不寫Student(於是也不能struct Student stu1;了,就必須是Stu stu1;)

typedef struct
    {
    int a;
    }Stu;

在c++裏

struct Student
{
	int a;
};   

於是就定義了結構體類型Student,聲明變量時直接

Student stu2;

在c++中如果用typedef的話,又會造成區別:

struct   Student  
{  
   int   a;  
}stu1;//stu1是一個變量  
typedef   struct   Student2  
{  
		int   a;  
}stu2;//stu2是一個結構體類型=struct Student  

使用時可以直接訪問

stu1.a=10

但是stu2則必須

stu2 s2;
s2.a=10;
typedef struct  
    {
    int num;
    int age;
    }aaa,bbb,ccc;

這相當於

typedef struct  
    {
    int num;
    int age;
    }aaa;
typedef aaa bbb;
typedef aaa ccc;

也就是說aaa,bbb,ccc三者都是結構體類型。聲明變量時用任何一個都可以,在c++中也是如此。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章