C/C++ 中定義結構體的幾種方法、初始化 以及別名的定義

定義結構體

定義結構體 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;
添加鏈接描述
添加鏈接描述

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