【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;
}
  • 地址传递
相关推荐
Mr.Lu ‍1 分钟前
C++开发,使用openCV API对图片进行压缩
开发语言·c++·opencv
大鹏的NLP博客1 分钟前
ONNX Runtime CUDA 推理优化实战:破解 C++ 比 Python 慢 28 倍的假象
c++·onnx·推理优化
ouynagda3 分钟前
Linux信号与进程间通信学习笔记
linux·笔记·学习
️学习的小王9 分钟前
AI Agent Skills进阶:调试、排错、实战开发与工程化落地
人工智能·经验分享·笔记·学习
kkkkkkkkkk_Z13 分钟前
学嵌入式和Linux应用编程|学习日记Day26:Linux进程完整学习笔记
linux·笔记·学习
kmomo..24 分钟前
Linux 进程间通信(IPC)学习笔记
linux·笔记·学习
zhonyu鱼28 分钟前
Drawpile:多人实时协作绘画,一起在同一块画布上画画
笔记·pdf·开源·开源软件
2601_949950631 小时前
在线刷题用什么小程序?认识一下能导资料、AI出题的练题簿
人工智能·学习·小程序·刷题·小程序推荐
HugoStudio_SWAN1 小时前
【按键反馈】C++ 实现键盘烟花秀
开发语言·c++·学习·程序人生
间歇性努力持续性发呆的野生快乐选手1 小时前
二分模板(整型,浮点型)
数据结构·c++·算法