欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++结构体详解

程序员文章站 2022-03-09 10:37:12
目录一、结构体的定义struct student{ string name; int age; int score;};二、创建具体的变量(3种)struct student s1;...

一、结构体的定义

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

二、创建具体的变量(3种)

struct student s1;
s1.name = "张三";
s1.age = 18;
s1.score = 90;
struct student s1 = {"李四" ,19 , 80 };
struct student
{
    string name;
    int age;
    int score;
}s3;
s3.name = "王五";
s3.age = 18;
s3.score = 89;

三、结构体数组

struct student stuarray[3] = 
{
    {"张三" , 20 , 92},
    {"李四" , 18 , 89},
    {"王五" , 24 , 95}
};
stuarray[2].name = "赵六";// 把王五改为赵六
//遍历结构体数组
for(int i =0; i < 3;i++)
{
    cout << "姓名:" << stuarray[i].name
         << "年龄:" << stuarray[i].age
         << "分数:" << stuarray[i].score <<endl;
}

四、结构体指针

利用操作符-> 可以通过结构体指针访问结构体属性。

struct student s = {"张三", 18, 90};
struct student *p = &s;
//通过指针访问结构体变量中的数据
cout << "姓名:" << p->name << endl; 

五、结构体嵌套结构体

struct student
{
    string name;
    int age;
    int score;
}
struct teacher
{
    int id;
    string name;
    int age;
    struct student stu;
}
teacher t;
t.stu.name;

六、结构体做函数参数

1、值传递

void printstudent(struct student s1)
{
    cout << "姓名:" <<s1.name << "年龄:" << s1.age << "分数" << s1.score;
}
int main(){
    struct student s1;
    s1.name = "张三";
    s1.age = 18;
    s1.score = 95;
    printstudent(s1);
}

2、地址传递

void printstudent(struct student * s1)
{
    cout << "姓名:" << p->name << "年龄:" << p->age << "分数" << p->score;
}
int main(){
    struct student s1;
    s1.name = "张三";
    s1.age = 18;
    s1.score = 95;
    printstudent(&s1);
}

七、结构体中const使用场景

void printstudent(const student * s1)
{
    cout << "姓名:" << p->name << "年龄:" << p->age << "分数" << p->score;
}
int main(){
    struct student s1;
    s1.name = "张三";
    s1.age = 18;
    s1.score = 95;
    printstudent(&s1);
}

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!