【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;
}
  • 地址传递
相关推荐
前路不黑暗@43 分钟前
Java项目:Java脚手架项目的模板服务和网关服务的实现(三)
java·开发语言·spring boot·git·学习·spring cloud·maven
山岚的运维笔记1 小时前
SQL Server笔记 -- 第50章 存储过程
数据库·笔记·sql·microsoft·oracle·sqlserver
寒秋花开曾相惜1 小时前
(学习笔记)2.1 信息存储(2.1.1 十六进制表示法)
笔记·学习
plus4s2 小时前
2月14日(76-78题)
c++·算法·图论
睡一觉就好了。2 小时前
迭代器失效问题
c++
-To be number.wan2 小时前
算法学习日记 |贪心算法
c++·学习·算法·贪心算法
知识分享小能手2 小时前
SQL Server 2019入门学习教程,从入门到精通,SQL Server 2019 规则、默认值和完整性约束 —— 语法详解与实战案例(11)
sql·学习·sqlserver
梦游钓鱼2 小时前
c++中一维数组和二维数组的应用
数据结构·c++·算法
神明不懂浪漫2 小时前
【第十三章】操作符详解,预处理指令详解
c语言·开发语言·经验分享·笔记
此刻觐神2 小时前
Windows学习笔记-18(MFC项目-制作快捷方式管理工具)
windows·笔记·学习·mfc