【C/C++ 学习笔记】结构体

【C/C++ 学习笔记】结构体

视频地址: Bilibili

结构体定义

语法:struct 结构体名 { 结构体成员列表 }

struct Student {
    string name;
    int age;
    int score;
}

int main() {
    struct Student stu1 = {
        'heyq',
        19,
        100
    };
}

结构体数组

struct 结构体名 数组名[元素格式] = { {}, {}, {}, … };

struct Student students[1] = {
    {
        '1',
        1,
        9
    },
    {
        '2',
        2,
        100
    }
};

结构体指针

利用操作符 -> 可以通过结构体指针访问结构体属性

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;
}

结构体嵌套结构体

struct Student {
    string name;
    int age;
    int score;
}

struct Teacher {
    string name;
    int age;
    struct Student *students;
}

结构体传参

  • 值传递
#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;
}
  • 地址传递

相关推荐

  1. 【C/C++ 学习笔记结构

    2024-03-16 21:06:01       43 阅读
  2. golang学习笔记——结构嵌套接口

    2024-03-16 21:06:01       32 阅读
  3. golang学习-结构

    2024-03-16 21:06:01       51 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-16 21:06:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-16 21:06:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-16 21:06:01       87 阅读
  4. Python语言-面向对象

    2024-03-16 21:06:01       96 阅读

热门阅读

  1. MySQL中的insert ignore into 和 insert into 使用方式

    2024-03-16 21:06:01       36 阅读
  2. MySql相关知识

    2024-03-16 21:06:01       40 阅读
  3. 关于uni-app 外部系统联登遇到的坑

    2024-03-16 21:06:01       43 阅读
  4. Elasticsearch(11) intervals的使用

    2024-03-16 21:06:01       44 阅读
  5. 分布式搜索引擎Elasticsearch中各种类型节点的作用

    2024-03-16 21:06:01       42 阅读
  6. Go 语言中的 Cond 机制详解

    2024-03-16 21:06:01       41 阅读
  7. xxl-job

    xxl-job

    2024-03-16 21:06:01      39 阅读
  8. 小程序配置服务器域名

    2024-03-16 21:06:01       38 阅读
  9. 简单了解跨域问题如何解决

    2024-03-16 21:06:01       46 阅读