【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;
}
  • 地址传递
相关推荐
殳翰2 小时前
下服务器端开发流程及相关工具介绍(C++)
开发语言·c++
青瓦梦滋3 小时前
协议定制/序列化-反序列化(Linux视角)
linux·服务器·网络·c++
山登绝顶我为峰 3(^v^)37 小时前
C/C++ 交叉编译方法
java·c语言·c++
星幻元宇VR8 小时前
公共安全实训展厅设备【人防知识学习系统】
科技·学习·安全
郝学胜-神的一滴10 小时前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal
心中有国也有家11 小时前
AtomGit Flutter 鸿蒙客户端:情绪日记的时间线实现
学习·flutter·华为·harmonyos
小小龙学IT12 小时前
C++ 并发编程深度解析:从内存模型到无锁数据结构
数据结构·c++
百里香酚兰12 小时前
【python学习笔记】pyttsx3库疑似只播报一次语音
笔记·python·学习
凯瑟琳.奥古斯特12 小时前
力扣1013三等分解法与C++实现
开发语言·c++·算法·leetcode·职场和发展