服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++结构体详解

C++结构体详解

2022-01-10 15:17SamRol C/C++

这篇文章主要介绍了C++ 结构体与共用体的的相关资料,帮助大家更好的理解和学习c++,感兴趣的朋友可以了解下,希望能够给你带来帮助

一、结构体的定义

?
1
2
3
4
5
6
struct Student
{
    string name;
    int age;
    int score;
};

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

?
1
2
3
4
struct Student s1;
s1.name = "张三";
s1.age = 18;
s1.score = 90;
?
1
struct Student s1 = {"李四" ,19 , 80 };
?
1
2
3
4
5
6
7
8
9
struct Student
{
    string name;
    int age;
    int score;
}s3;
s3.name = "王五";
s3.age = 18;
s3.score = 89;

三、结构体数组

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}

四、结构体指针

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

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

五、结构体嵌套结构体

?
1
2
3
4
5
6
7
8
9
10
11
12
13
struct student
{
    String name;
    int age;
    int score;
}
struct teacher
{
    int id;
    String name;
    int age;
    struct student stu;
}
?
1
2
teacher t;
t.stu.name;

六、结构体做函数参数

1、值传递

?
1
2
3
4
5
6
7
8
9
10
11
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、地址传递

?
1
2
3
4
5
6
7
8
9
10
11
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使用场景

?
1
2
3
4
5
6
7
8
9
10
11
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);
}

总结

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

原文链接:https://blog.csdn.net/qq_26082507/article/details/120396912

延伸 · 阅读

精彩推荐