【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;
}
  • 地址传递
相关推荐
惊讶的猫32 分钟前
c++基础
开发语言·c++
im_AMBER4 小时前
Leetcode 38
笔记·学习·算法·leetcode
koo3645 小时前
李宏毅机器学习笔记32
人工智能·笔记·机器学习
Code_Shark5 小时前
AtCoder Beginner Contest 426 题解
数据结构·c++·算法·数学建模·青少年编程
仰泳的熊猫5 小时前
LeetCode:698. 划分为k个相等的子集
数据结构·c++·算法·leetcode
xlq223225 小时前
7(内存管理)(上)(了解)
c++
正经教主6 小时前
【Trae+AI】和Trae学习搭建App_01(附加可略过):测试Trae的后端功能
学习·app
桃子不吃李子7 小时前
axios的二次封装
前端·学习·axios
WBluuue7 小时前
数据结构与算法:摩尔投票算法
c++·算法·leetcode
明明真系叻7 小时前
最优传输理论学习(1)+PINN文献阅读
深度学习·学习