c++ 基础知识-结构体
1.初始化结构体,结构体数组
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
};
int main()
{
Student stuArr[] = {{"a",1},{"b",2},{"c",3}};
stuArr[1].name = "d";
stuArr[1].age = 4;
for (int i = 0;i<sizeof(stuArr)/sizeof(stuArr[0]);i++)
{
cout<<"name :"<<stuArr[i].name
<<" "
<<"age :"<<stuArr[i].age<<endl;
}
return 0;
}
2.结构体指针
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
};
int main()
{
Student stu;
stu.name = "a";
stu.age = 2;
Student *p = &stu;
cout<<"name :"<<p->name<<endl;
cout<<"age :"<<p->age<<endl;
return 0;
}
3.结构体嵌套
#include <iostream>
#include <string>
using namespace std;
struct Learn
{
int math;
int english;
};
struct Student
{
string name;
int age;
struct Learn learn;
};
int main()
{
Student stu;
stu.name = "a";
stu.age = 5;
stu.learn.english = 10;
stu.learn.math = 20;
cout<<stu.learn.english<<endl;
cout<<stu.learn.math<<endl;
return 0;
}
4.结构体作为函数参数
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
};
void CoutStruct(Student * stu);
int main()
{
Student stu;
stu.age = 19;
stu.name = "a";
Student * p = &stu;
CoutStruct(p);
cout<<"age: "<<stu.age<<endl;
return 0;
}
void CoutStruct(Student * stu)
{
stu->age = 30;
cout<<"age: "<<stu->age<<endl;
cout<<"name: "<<stu->name<<endl;
}