【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;
}
  • 地址传递
相关推荐
qqty12178 分钟前
Java进阶学习之路
java·开发语言·学习
WHS-_-20229 分钟前
Python 算法题学习笔记一
python·学习·算法
_李小白17 分钟前
【OSG学习笔记】Day 22: StateSet 与 StateAttribute (渲染状态)
笔记·学习
c++逐梦人1 小时前
C++11——— 包装器
开发语言·c++
zzh0811 小时前
Mysql数据库备份与恢复笔记
数据库·笔记·mysql
TorrieLeung2 小时前
碎片学习|外贸tob 一手交钱一手交货
学习·tob·外贸销售·工地英语
十年编程老舅2 小时前
Linux 多线程高并发编程:读写锁的核心原理与底层实现
linux·c++·linux内核·高并发·线程池·多线程·多进程
wildlily84272 小时前
C++ Primer 第5版章节题 第十三章(二)
开发语言·c++
xiaoye-duck2 小时前
【C++:unordered_set和unordered_map】 深度解析:使用、差异、性能与场景选择
开发语言·c++·stl
老约家的可汗3 小时前
list 容器详解:基本介绍与常见使用
c语言·数据结构·c++·list