C++快速笔记 8 结构体
  TEZNKK3IfmPf 2023年11月15日 29 0

8 结构体

8.1 结构体概念

结构体属于用户自定义的数据类型。

8.2 结构体定义和使用

语法:struct 结构体名 {结构体成员列表};使用.访问成员。 e:

// 结构体定义
struct Student {
    string name;
    int age;
    int score;
};

//创建student
//1. (在C++中,struct可以省略)
struct Student s1;
s1.name = "张三";//...

//2.
struct Student s2 = {"李四", 19, 80};

// 3.定义结构体在最后的}后面创建。不推荐

8.3 结构体数组

结构体组成的数组

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

//结构体数组
Student arr[3] = {
    {"张三", 18 ,80},
    {"李三", 19 ,85},
    {"李四", 18 ,90}
};

8.4 结构体指针

利用->用指针访问结构体属性。

Student std = {"张三", 18 ,80};
Student  * p = & stu;
cout<< p->name <<endl;

8.5 结构体嵌套

结构体中的成员可以是结构体。

8.6 结构体作为函数参数

-值传递 -地址传递

//-值传递
void print_Student(Student stu){
    cout << stu.name << stu.age<<stu.score;
}

//-地址传递
void print_Student2(Student *stu){
    cout << stu->name << stu->age << stu->score;
}

8.7 结构体中const

const使用示例:

void print_Student2(const Student *stu){
    //stu->age = 100 // 不能修改。
    cout << stu->name << stu->age << stu->score;
}

使用指针节省内存空间,并且避免 误修改的风险。

8.8 结构体案例

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   24天前   38   0   0 C++
  TEZNKK3IfmPf   24天前   26   0   0 指针C++
  TEZNKK3IfmPf   2024年05月31日   24   0   0 算法C++
TEZNKK3IfmPf