【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;
}
  • 地址传递
相关推荐
挥剑决浮云 -7 分钟前
Linux 之 安装软件、GCC编译器、Linux 操作系统基础
linux·服务器·c语言·c++·经验分享·笔记
丶Darling.24 分钟前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
labuladuo52034 分钟前
Codeforces Round 977 (Div. 2) C2 Adjust The Presentation (Hard Version)(思维,set)
数据结构·c++·算法
小柯J桑_1 小时前
C++:STL简介
c++·stl
新晓·故知1 小时前
<基于递归实现线索二叉树的构造及遍历算法探讨>
数据结构·经验分享·笔记·算法·链表
咖啡里的茶i1 小时前
C++之继承
c++
魔理沙偷走了BUG2 小时前
【数学分析笔记】第4章第4节 复合函数求导法则及其应用(3)
笔记·数学分析
NormalConfidence_Man2 小时前
C++新特性汇总
开发语言·c++
风清扬_jd2 小时前
Chromium 中JavaScript Fetch API接口c++代码实现(二)
javascript·c++·chrome