C++基础六-结构体

/*C/C++ 数组允许定义可存储相同类型数据项的变量,但是结构是 C++ 中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。*/
#include <iostream>
#include <string>
using namespace std;

//1.定义结构体

struct Food { string name; int price; };
struct Member { string name; int age; int score; struct Food f1; };

void Printstruct(Member m) { cout <<"函数中"<< m.name <<endl; };


int main() {
    //2.结构体创建,通过(.)赋值与访问。
    //2.1
    struct Member m1;
    m1.name = "Jack";
    m1.age = 20;
    m1.score = 100;
    //2.2
    struct Member m2 = { "mick",19,60 };
    cout << m1.name << endl;
    cout << m2.name << endl;
    cout << endl;


    /*3.结构体数组*/
    struct Member arr[3] = {
        {"Ruby",20,33},
        {"Python",22,22},
        {"Java",55,55}
    };
    for (int i = 0; i < 3; i++)
    {
        cout << arr[i].name;
        cout << arr[i].age;
        cout << arr[i].score;
        cout << endl;
    }


    /*4.嵌套结构体*/
    struct Member m3 = { "C++",66,77, {"Apple",2000} };
    cout << "嵌套结构体" << endl;
    cout << m3.age << m3.score << m3.f1.name << m3.f1.price << endl;

    /*5.结构体当函数参数*/
    Printstruct(m3);


    return 0;
}
/*C/C++ 数组允许定义可存储相同类型数据项的变量,但是结构是 C++ 中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。*/
#include <iostream>
#include <string>
using namespace std;

//1.定义结构体

struct Food { string name; int price; };
struct Member { string name; int age; int score; struct Food f1; };

void Printstruct(Member m) { cout <<"函数中"<< m.name <<endl; };


int main() {
    //2.结构体创建,通过(.)赋值与访问。
    //2.1
    struct Member m1;
    m1.name = "Jack";
    m1.age = 20;
    m1.score = 100;
    //2.2
    struct Member m2 = { "mick",19,60 };
    cout << m1.name << endl;
    cout << m2.name << endl;
    cout << endl;


    /*3.结构体数组*/
    struct Member arr[3] = {
        {"Ruby",20,33},
        {"Python",22,22},
        {"Java",55,55}
    };
    for (int i = 0; i < 3; i++)
    {
        cout << arr[i].name;
        cout << arr[i].age;
        cout << arr[i].score;
        cout << endl;
    }


    /*4.嵌套结构体*/
    struct Member m3 = { "C++",66,77, {"Apple",2000} };
    cout << "嵌套结构体" << endl;
    cout << m3.age << m3.score << m3.f1.name << m3.f1.price << endl;

    /*5.结构体当函数参数*/
    Printstruct(m3);


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值