结构体定义和使用
语法:struct 结构体名 { 结构体成员列表 };
通过结构体创建变量的方式有三种:
- struct 结构体名 变量名
- struct 结构体名 变量名 = { 成员1值 , 成员2值…}
- 定义结构体时顺便创建变量
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
}stu3;
// 方式3:定义了一个结构体变量名为stu3
int main(int argc,char* argv[])
{
// 方式1:定义结构体变量
student stu1;
stu1.name = "liming";
stu1.age = 24;
cout<<stu1.name<<" "<<stu1.age<<endl;
// 方式2:定义了结构体变量
student stu2 = {"wanglei",24};
cout<<stu2.name<<" "<<stu2.age<<endl;
}
结构体指针
作用:通过指针访问结构体中的成员
- 利用操作符
->
可以通过结构体指针访问结构体属性
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
};
int main(int argc,char* argv[])
{
student stu1;
student* ptr_stu1 = &stu1;
ptr_stu1->name = "liming";
ptr_stu1->age = 24;
cout<<ptr_stu1->name<<" "<<ptr_stu1->age<<endl;
}
结构体嵌套结构体
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
struct teacher
{
string name;
int age;
student stu;
};
int main(int argc,char* argv[])
{
teacher t1;
t1.name = "wanghong";
t1.age = 45;
t1.stu.name = "liming";
t1.stu.age = 24;
t1.stu.score = 100;
cout<<"the score of "<<t1.stu.name<<" is "<<t1.stu.score<<endl;
}
结构体作函数参数
作用:将结构体作为参数向函数中传递
传递方式有两种:
- 值传递
- 地址传递
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void value_transmit(student stu1)
{
stu1.score = 60;
cout<<"the score of "<<stu1.name<<" is "<<stu1.score<<endl;
return;
}
void add_transmit(student* stu1)
{
stu1->score = 60;
cout<<"the score of "<<stu1->name<<" is "<<stu1->score<<endl;
return;
}
int main(int argc,char* argv[])
{
student stu1;
stu1.name = "liming";
stu1.score = 100;
stu1.age = 20;
cout<<"the score of "<<stu1.name<<" is "<<stu1.score<<endl;
value_transmit(stu1);
cout<<"the score of "<<stu1.name<<" is "<<stu1.score<<endl;
add_transmit(&stu1);
cout<<"the score of "<<stu1.name<<" is "<<stu1.score<<endl;
}