定義結構體
定義結構體 Student 並調用裏面的變量age
C版本:
- 方法1. 定義結構體
struct Student{
int id;
int age;
};
調用:
struct Student stu;
int b = stu.age;
- 方法2.定義結構體
typedef struct Student {
int id;
int age;
}Stud;
調用
Stud stu;
stu.age = 10;
int b = stu.age;
如果沒有typedef ,則C語言中需要用struct Student stu來定義對象。
Stud 相當於是struct Student的別稱
- 方法3.省略Student
typedef struct {
int id;
int age;
}Stud;
調用
Stud stu;
stu.age = 10;
int b = stu.age;
C++版本
直接定義
- 方法1. 有初始化
struct Stud {
int id;
int age;
{
id = 1;
age = 10;
};
調用
Stud stu;
stu.age = 10;
int b = stu.age;
- 方法2.使用typedef進行時,有別名,需要定義對象。
typedef struct Student {
int id;
int age;
Student ()
{
id = 1;
age = 10;
}
}Stud;
調用時
Stud stu;
stu.age = 10;
int b = stu.age;
- 3.使用using 並初始化
using Student = struct {
int id = 1;
int age = 10;
};
調用
Student stu;
stu.age = 10;
int b = stu.age;
【定義別名】
typedef 舊的 新的
注意使用typedef
方法1. typedef std::vector name_list;