【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;
}
  • 地址传递
相关推荐
郝学胜-神的一滴16 分钟前
Linux下的阻塞与非阻塞模式详解
linux·服务器·开发语言·c++·程序人生·软件工程
一只小风华~30 分钟前
学习笔记:Vue Router 中的链接匹配机制与样式控制
前端·javascript·vue.js·笔记·学习·ecmascript
月临水2 小时前
Redis 学习笔记(二)
redis·笔记·学习
摇滚侠2 小时前
Spring Boot 3零基础教程,条件注解,笔记09
java·spring boot·笔记
Nan_Shu_6142 小时前
学习SpringBoot
java·spring boot·后端·学习·spring
●VON2 小时前
重生之我在大学自学鸿蒙开发第二天-《MVVM模式》
学习·华为·harmonyos
Samsong3 小时前
《C++ Primer Plus》读书笔记 第二章 开始学习C++
c++·后端
你真的可爱呀3 小时前
uniapp学习【vue3在uniapp中语法,使用element,使用uView UI】
学习·uni-app
想你依然心痛3 小时前
Spark大数据分析与实战笔记(第六章 Kafka分布式发布订阅消息系统-01)
笔记·分布式·spark
Rubisco..3 小时前
牛客周赛 Round 111
数据结构·c++·算法