(4.1) 结构体创建
#include<iostream>
#include<string>
using namespace std;
//结构体一般创建在主函数之前
struct Student
{
//结构体的默认访问权限为公共
string name;
int age;
};
int main()
{
struct Student s1; //struct可以省略
//第一种初始化方式
s1.name = "张三";
s1.age = 18;
//第二种初始化方式
Student s2 = {"李四",19};
system("pause");
//结构体数组的初始化
Student sArr[] = { {"张三",18},{"李四",19},{"王五",20} };
sArr[2].name = "赵六"; //修改第三个学生的名字
return 0;
}
(4.2) 结构体指针
结构体指针(或类的对象指针)要用
->符号访问成员(或类的对象的属性和行为)。
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
int age;
};
int main()
{
Student s = {"张三",18};
Student* p = &s;
cout << "姓名:" << p->name << "\t年龄:" << p->age << endl;
system("pause");
return 0;
}
(4.3) 结构体嵌套
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
int age;
};
struct Teacher
{
string name;
int age;
Student s;
};
int main()
{
Teacher t = {"王老师",40,{"小明",18}};
system("pause");
return 0;
}
(4.4) 结构体参数
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
int age;
};
void studentPrint1(Student s) //值传递
{
s.age = 18;
cout << "姓名:" << s.name << "\t年龄:" << s.age << endl;
}
void studentPrint2(Student* s) //地址传递
{
s->age = 19;
cout << "姓名:" << s->name << "\t年龄:" << s->age << endl;
}
int main()
{
Student s = {"张三",18};
studentPrint1(s);
studentPrint2(&s);
system("pause");
return 0;
}
《 C + + S Y N T A X 》 系 列 博 客 创 作 参 考 资 料 来 源 《C++\ SYNTAX》系列博客创作参考资料来源 《C++ SYNTAX》系列博客创作参考资料来源
- 《黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难》@黑马程序员.https://www.bilibili.com.
博 客 创 作 : A i d e n L e e 博客创作:Aiden\ Lee 博客创作:Aiden Lee
特别声明:文章仅供学习参考,转载请注明出处,严禁盗用!
本文详细介绍了C++中结构体的创建、结构体指针的使用、结构体嵌套结构以及结构体作为参数的应用实例。通过实例学习如何定义、初始化和操作复杂的数据结构。
1080

被折叠的 条评论
为什么被折叠?



