6.1重学C++之【认识结构体】

#include<iostream>
#include<string>
using namespace std;


/*
    结构体
    一些数据类型的集合
    用户自定义的数据类型
    允许存放不同的数据类型
*/


// 结构体定义
struct Student{
    string name;
    int age;
    int score; // 注意,最后一项元素末尾也要加分号,不然报错
};


int main(){
    // 结构体变量的三种创建方式
    // 前两种方式用的较多

    // 1
    struct Student s1;
    s1.name = "张三"; // 给结构体变量的属性赋值
    s1.age = 18;
    s1.score = 100;
    cout << "姓名:" << s1.name << ",年龄:" << s1.age << ",分数:" << s1.score << endl;

    // 2
    struct Student s2 = {"李四", 19, 80};
    cout << "姓名:" << s2.name << ",年龄:" << s2.age << ",分数:" << s2.score << endl;

    // 3 在创建结构体的同时创建空变量
    struct Student_1{
        string name;
        int age;
        int score;
    }s3;
    s3.name = "王五";
    s3.age = 20;
    s3.score = 60;
    cout << "姓名:" << s3.name << ",年龄:" << s3.age << ",分数:" << s3.score << endl;

    // 注意,C++中创建结构体变量时struct关键字可以省略,例如:Student s1,Student s2


    return 0;
}

posted @   yub4by  阅读(17)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示