0

【笔记】C++结构体

 1 year ago
source link: https://feiju12138.github.io/2022/08/12/C-%E7%BB%93%E6%9E%84%E4%BD%93/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C++结构体学习笔记

定义结构体

struct 结构体名
{
成员变量类型 成员变量名
...
};

创建结构体变量

struct 结构体名 结构体变量名;
  • 创建结构体变量时,可以省略struct关键字

创建结构体变量时直接为成员变量赋值

  • 根据成员变量的顺序初始化成员变量的值
struct 结构体名 结构体变量名 = { 值, ... }

定义结构体时直接创建结构体变量

struct 结构体名
{
成员变量类型 成员变量名
...
}结构体变量名;

访问结构体变量的成员变量

获取成员变量的值

结构体变量名.成员变量名;

修改成员变量的值

结构体变量名.成员变量名;

结构体数组

创建一个结构体数组变量

  • 通过结构体的定义,创建一个结构体数组变量
struct 结构体名 结构体变量名[数组长度] =
{
{值, ...},
...
{值, ...}
};

获取结构体数组成员变量的值

结构体变量名[下标].成员变量名;

修改结构体数组成员变量的值

结构体变量名[下标].成员变量名 = 值;

结构体指针

创建一个结构体指针

struct 结构体名 结构体变量名;
struct 结构体名 * 指针名 = &结构体变量名;

获取结构体成员变量的值

指针名->结构体成员变量名;

修改结构体成员变量的值

指针名->结构体成员变量名 = 值;

结构体嵌套

struct child
{
string name;
};

struct parent
{
string name;
struct child son;
};

int main()
{
struct parent father;
father.name = "张三"
father.son.name = "张三丰";
}

结构体作为函数的参数

void 函数名(struct 结构体名 结构体变量名)
{
结构体变量名.成员变量名;
...
}
void 函数名(struct 结构体名 * 指针名)
{
指针名->成员变量名;
...
}

传递常量地址

  • 当某些应当执行读操作的函数传递结构体的地址作为参数时,可以用const关键字进行修饰,使之不可被修改,防止误操作
void 函数名(const struct 结构体名 * 指针名)
{
指针名->成员变量名;
...
}

哔哩哔哩——黑马程序员


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK