美文网首页
1.结构体

1.结构体

作者: lxr_ | 来源:发表于2020-12-26 20:05 被阅读0次

    #include<iostream>

    using namespace std;

    struct  student

    {

        string name;

        int age;

        int score;

    }s3;

    struct  teacher

    {

        int id;

        string name;

        int age;

        student stu;

    };

    int main()

    {

        //创建具体学生,C++中struct可省略

        //1.struct student s1;

        struct student s1;

        student s5;//省略struct

        s1.name = "xiansifan";

        s1.age = 22;

        s1.score = 100;

        cout << "姓名:" << s1.name << endl;

        cout << "年龄:" << s1.age << endl;

        cout << "分数:" << s1.score << endl;

        //2.struct student s2={....};

        struct student s2 = { "xian",21,90 };

        cout << "姓名:" << s2.name << endl;

        cout << "年龄:" << s2.age << endl;

        cout << "分数:" << s2.score << endl;

        //3.在创建结构体时顺便创建结构体变量

        s3.name = "sifan";

        s3.age = 90;

        s3.score = 89;

        cout << "姓名:" << s3.name << endl;

        cout << "年龄:" << s3.age << endl;

        cout << "分数:" << s3.score << endl;

        //创建结构体数组

        struct student arr[3] =

        {

            {"张三",13,56},

            {"李四",34,34},

            {"王五",34,55}

        };

        arr[2].age = 89;

        arr[2].name = "赵六";

        arr[2].score = 67;

        for (int i = 0; i < 3; i++)

        {

            cout << arr[i].name;

            cout << "  ";

            cout << arr[i].age;

            cout << "  ";

            cout << arr[i].score << endl;

        }

        //结构体指针

        student* p = &s1;

        cout << p->name << endl;

        cout << p->age << endl;

        cout << p->score<<endl;

        cout << "结构体嵌套:" << endl;

        teacher t;

        t.id = 100000;

        t.name = "feifei";

        t.age = 90;

        t.stu.name = "xiansifan";

        t.stu.age = 22;

        t.stu.score = 90;

        cout << t.id << endl;

        cout << t.name << endl;

        cout << t.age << endl;

        cout << t.stu.name << endl;

        cout << t.stu.age << endl;

        cout << t.stu.score << endl;

        system("pause");

        return 0;

    }

    相关文章

      网友评论

          本文标题:1.结构体

          本文链接:https://www.haomeiwen.com/subject/rkognktx.html