定义结构体
定义结构体 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;
方法2.using name_list = std::vector;