加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++之结构体

发布时间:2020-12-16 09:05:42 所属栏目:百科 来源:网络整理
导读:一、结构体定义 结构体属于用户自定义的类型,允许用户存储不同的数据类型。 语法:struct 结构体名{结构体成员列表}; 通过结构体创建变量有三种方式: struct 结构体名 变量名 struct 结构体名 变量名={成员1值,成员2值...} 定义结构体时顺便创建变量 一般

一、结构体定义

结构体属于用户自定义的类型,允许用户存储不同的数据类型。

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

通过结构体创建变量有三种方式:

  • struct 结构体名 变量名
  • struct 结构体名 变量名={成员1值,成员2值...}
  • 定义结构体时顺便创建变量

一般使用前两种,因为第三种在定义时创建的变量容易被人所忽略。

#include <iostream>
using namespace std;
struct Student {
    string name;
    int age;
    float score;
}s3;

 main() {    
    //创建的时候struct关键字可以省略
     Student s1;
    s1.name = "tom";
    s1.age = 12;
    s1.score = 99;
    cout << name:" << s1.name << age:" << s1.age << score:" << s1.score << endl;
    struct Student s2 ={jack",15,1)">98};
    s3.name = bob;
    s3.age = 19;
    s3.score = 97;
    system(pause);
    return 0;
}

二、结构体数组

作用:将自定义的结构体放入到数组中方便维护。

语法:struct 结构体名 数组名[元素个数] = {{},{},...{}}

#include <iostream>
 score;
};

结构体数组定义
    struct Student stuArr[3]
    {
        { 19,1)">},{ 22,1)"> },};
    可以修改值或者在这里进行赋值
    stuArr[2].name = mike;
    获取数组的长度
    int length = sizeof(stuArr) / sizeof(stuArr[]);
    遍历数组
    for (int i = 0; i < length; i++) {
        cout << stuArr[i].name << stuArr[i].age << stuArr[i].score << endl;
    }
    system(三、结构体指针

作用:通过指针来访问结构体中的成员

#include <iostream>
struct Student s = { 12,1)"> };
    Student* p = &s;
    需要使用->来访问
    cout << p->name << p->age << p->score << endl;
    system(四、结构体嵌套结构体

#include <iostream>
 std;

 score;
};
 Teacher {
     id;
     age;
    Student stu;
};


 main() {
     Teacher t;
    t.id = 1;
    t.name = joke;
    t.age = 45struct Student stu = {  };
    t.stu = stu;
    cout << t.id << t.name << t.age << t.stu.name << t.stu.age << t.stu.score <<五。结构体做函数参数

作用:将结构体作为参数向函数传递。

传递方式有两种:值传递、引用传递。

值传递:

#include <iostream>
值传递
void printStudent(Student stu) {
    stu.name = ;
    stu.age = 22;
    stu.score = 90结构体中的stu信息:" << endl;
    cout << stu.name << ," << stu.age << " << stu.score << endl;
}


 };
    cout << 未传入函数之前的结构体值: endl;
    printStudent(stu);
    cout << 传入函数之后的结构体值:" << stu.score<<;
}

输出:

?

引用传递:

#include <iostream>
void printStudent(Student* stu) {
    stu->name = ;
    stu->age = ;
    stu->score =  endl;
    cout << stu->name << " << stu->age << " << stu->score << };
    struct Student* p = &stu;
    cout <<  endl;
    printStudent(p);
    cout << ;
}

输出:

?

六、结构体中const的使用场景

作用:用const防止误操作?

#include <iostream>
void printStudent(const Student* stu) {
    /*这里就不能进行修改了
    stu->name = "jack";
    stu->age = 22;
    stu->score = 90;
    */
    cout << ;
}

输出:

?

只需要记住,用const修饰的数据类型就不能再进行更改。?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读