【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;
}
  • 地址传递
相关推荐
飞鸿踏雪(蓝屏选手)3 分钟前
137 ≤ Chrome 主密钥获取研究
c++·chrome·windows·网络安全·逆向分析
爱看大明王朝15661 小时前
磁件学习-磁性元器件的极限计算
笔记·学习
东风破1371 小时前
DM8达梦共享存储集群DSC搭建步骤
数据库·学习·dm达梦数据库
问心无愧05131 小时前
ctf show web入门 40
笔记
星幻元宇VR2 小时前
VR科普大空间:沉浸式公共教育新模式
科技·学习·安全·vr·虚拟现实
@蓝莓果粒茶3 小时前
【Unity笔记】保姆级AssetBundle详解(含代码+避坑指南)
笔记·游戏·unity
kobesdu4 小时前
【ROS2实战笔记-20】ROS2 bag 录播与时间模拟:从基础操作到高级调试技巧
笔记·机器人·ros·ros2
笨鸟先飞的橘猫4 小时前
MMO游戏中的“跨服团队副本”匹配与状态同步系统
分布式·学习·游戏·lua·skynet
kobesdu4 小时前
【ROS2实战笔记-18】ROS2 通信的隐秘控制:DDS 配置参数如何决定系统性能
网络·人工智能·笔记·机器人·开源·ros·人形机器人
雨落在了我的手上5 小时前
如何学习java?
java·开发语言·学习