【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;
}
  • 地址传递
相关推荐
Q741_1473 分钟前
力扣高频面试题详解 数组 链表 力扣 56.合并区间 力扣 160.相交链表 C++ 每日练习
c++·算法·leetcode·链表·数组·哈希
夜泉_ly5 分钟前
泉面 TOP150 -讲一下智能指针?
c++
深蓝轨迹6 分钟前
黑马点评-day02-缓存笔记
redis·笔记·缓存·mybatis
小陈phd7 分钟前
多模态大模型学习笔记(二十三)——一文搞懂数虚拟人:从定义、分类到核心技术全景
笔记·学习
糖果店的幽灵7 分钟前
【大模型】大模型学习总结之机器学习-3.模型评估
人工智能·学习·机器学习
2301_7938046911 分钟前
C++中的备忘录模式
开发语言·c++·算法
煤球王子14 分钟前
学而时习之:C++中的标准模板5.2
c++
qq_2837200515 分钟前
Qt QML 中为 ComBox设置鸿蒙字体(HarmonyOS Sans)——适配 Qt 5.6.x 与 Qt 5.12+
c++·qt·harmonyos
2501_9454235416 分钟前
C++编译期多态实现
开发语言·c++·算法