1.在C语言中,struct关键字用于定义结构体,而typedef关键字用于为数据类型提供别名。
//以 struct Name_A 定义结构体
struct Name_A
{
};
//以 struct Name_A 定义结构体,在申请新的 Name_A 变量时需要下面的写法
struct Name_A Name1;
//==============================================================
//以 typedef struct Name_B 定义结构体
typedef struct Name_B
{
}Name_C;
//以 typedef struct Name_B 定义结构体,在申请新的 Name_B 变量时可以省略 struct
//Name_C是 Name_B 的别名
Name_B Name1; //这两个写法都是对的
Name_C Name1;
代码:
//struct写法
struct Name_A
{
int Green;
int Red;
int Blue;
};
struct Name_A Array[5]
{
{10, 15, 20},
{1, 3, 5},
{36, 60, 90},
{22, 32, 42},
{3, 6, 9}
};
//=================================================================================================
//typedef struct写法
typedef struct Name_B
{
int Green;
int Red;
int Blue;
}Name_C;
Name_B Array[5] =
{
{10, 15, 20},
{1, 3, 5},
{36, 60, 90},
{22, 32, 42},
{3, 6, 9}
};
Name_C Array[5] =
{
{10, 15, 20},
{1, 3, 5},
{36, 60, 90},
{22, 32, 42},
{3, 6, 9}
};
2.在c++中可以不需要typedef就可以Name_A Name1,因为在c++中struct也是一种类,所以可以直接使用Name_A Name1来定义一个Name_A的对象,但c中却不可以。
struct Name_A
{
int Green;
int Red;
int Blue;
};
Name_A Array[5]
{
{10, 15, 20},
{1, 3, 5},
{36, 60, 90},
{22, 32, 42},
{3, 6, 9}
};
typedef struct Name_B
{
int Green;
int Red;
int Blue;
}Name_C;
Name_B Array[5] =
{
{10, 15, 20},
{1, 3, 5},
{36, 60, 90},
{22, 32, 42},
{3, 6, 9}
};
Name_C Array[5] =
{
{10, 15, 20},
{1, 3, 5},
{36, 60, 90},
{22, 32, 42},
{3, 6, 9}
};
3.结构体定义和使用
语法:struct 结构体名 { 结构体成员列表 }
通过结构体创建变量的方式有三种:
-
struct 结构体名 变量名
-
struct 结构体名 变量名 = { 成员1值 , 成员2值…}
-
定义结构体时顺便创建变量
//结构体定义 struct Name_A { //成员列表 string name; //姓名 int age; //年龄 int score; //分数 }Name3; //结构体变量创建方式3 int main() { //结构体变量创建方式1 C中:struct 关键字不可以省略 C++中:struct 关键字可以省略 struct Name Name1; Name1.name = "张三"; Name1.age = 18; Name1.score = 100; //================================================================================ //结构体变量创建方式2 C中:struct 关键字不可以省略 C++中:struct 关键字可以省略 struct Name_A Name2 = { "李四",19,60 }; Name3.name = "王五"; Name3.age = 18; Name3.score = 80; }