【C/C++ 学习笔记】结构体

【C/C++ 学习笔记】结构体

视频地址: Bilibili

结构体定义

语法:struct 结构体名 { 结构体成员列表 }

c++ 复制代码
struct Student {
    string name;
    int age;
    int score;
}

int main() {
    struct Student stu1 = {
        'heyq',
        19,
        100
    };
}

结构体数组

struct 结构体名 数组名[元素格式] = { {}, {}, {}, ... };

c++ 复制代码
struct Student students[1] = {
    {
        '1',
        1,
        9
    },
    {
        '2',
        2,
        100
    }
};

结构体指针

利用操作符 -> 可以通过结构体指针访问结构体属性

c++ 复制代码
struct Student {
    string name;
    int age;
    int score;
}

int main() {

    // 创建结构体变量
    struct Student stu1 = { 'heyq', 18, 100 };

    // 创建结构体指针
    struct Student *p = &stu1;

    // 访问成员变量
    cout << p->name << endl;

    return 0;
}

结构体嵌套结构体

c++ 复制代码
struct Student {
    string name;
    int age;
    int score;
}

struct Teacher {
    string name;
    int age;
    struct Student *students;
}

结构体传参

  • 值传递
c++ 复制代码
#include <iostream>
#include <string>

using namespace std;

struct Student {
    string name;
}

void printStudent1(struct Student s) {
    s.name = 'hjh';
    cout >> s.name >> endl;
}

void printStudent2(struct Student *p) {
    p->name = 'hjh';
    cout >> p->name >> endl;
}

int main() {
    struct Student s1 = { 'hyq' };

    printStudent1(s1);
    printStudent2(&s1);

    cout << s1.name << endl;
    return 0;
}
  • 地址传递
相关推荐
arron88991 分钟前
自训练yolo模型自主学习性能持续提升思路
学习·yolo·目标跟踪
陌上明苏11 分钟前
.NET1-异步方法、LINQ
学习
挖矿大亨12 分钟前
c++中值传递时是如何触发拷贝构造函数的
开发语言·c++
青衫码上行16 分钟前
【JavaWeb学习 | 第23篇】监听器、RBAC权限模型
java·学习·servlet·jsp
顶点多余24 分钟前
继承和多态
c++·servlet
sbc-study43 分钟前
comsol例题学习-旋转晶片电镀-稀物质传递+二次电流分布+电极,壳+层流
学习·comsol·二次电流分布·稀物质传递·电极,壳·多物理场耦合·层流
智算菩萨1 小时前
【Python基础】AI的“重复学习”:循环语句(for, while)的奥秘
人工智能·python·学习
stars-he1 小时前
二极管峰值包络检波电路仿真学习笔记
笔记·学习
炽烈小老头1 小时前
【每天学习一点算法 2025/12/25】爬楼梯
学习·算法·动态规划
songyuc1 小时前
VCD学习笔记
学习