【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;
}
  • 地址传递
相关推荐
LuckyRich13 分钟前
【RabbitMq C++】消息队列组件
c++·分布式·rabbitmq
柴薪之王、睥睨众生31 分钟前
(自用)Java学习-5.8(总结,springboot)
java·开发语言·spring boot·学习·mybatis
让我们一起加油好吗31 分钟前
【C++】模板(初阶)
开发语言·c++·visualstudio·模板·泛型编程
Run_Teenage2 小时前
C++类和对象:运行符重载、取地址运算符重载、const 修饰的类如何作为参数
开发语言·c++
一只小bit2 小时前
More Effective C++:改善编程与设计(上)
开发语言·c++·方法·技巧
李匠20245 小时前
C++GO语言微服务之图片、短信验证码生成及存储
开发语言·c++·微服务·golang
UpUpUp……5 小时前
HTML简单语法标签(后续实操:云备份项目)
笔记·html
小彭律师6 小时前
门禁人脸识别系统详细技术文档
笔记·python
是孑然呀7 小时前
【小记】word批量生成准考证
笔记·学习·excel
ll7788119 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法