结构体
结构体的定义
1.先定义一个结构体,按照需求定义其内含的数个变量类型
struct student{
string name;
int age;
int score;
}(主函数外)
2.定义一个结构体类型的变量组
① struct 结构体名称 变量名称
struct student s1;
s1.name="张三";
s1.age=18;
s1.score=100;(主函数内)
② struct 结构体名称 变量名称={成员1值,成员2值...}
struct student s1={"李四",18,80};(主函数内)
③ 在定义结构体时顺便创建结构体变量
struct student{
string name;
int age;
int score;
}s3;
int main (){
s1.name="马五";
s1.age=18;
s1.score=100;
}
————————————————————————————
结构体数组
struct 结构体名 结构体数组名[元素个数]={{ },{ },{ },..{ }};
为数组中的元素赋值
student s3[i].name="马文";
————————————————————————————
结构体指针
1.创建一个结构体变量
struct student s1={"张三",18,100}
2.通过指针指向结构体变量
student *p=&s1;
3.通过指针访问结构体变量中的数据(通过“->”操作符访问成员属性)
cout<< p->name << p->age << p->score;
————————————————————————————
嵌套结构体
struct teacher{
int id;
string name;
int age;
struct student stu;
}
struct student{
string name;
int age;
int score;
}
teacher t;
t.id=10086;
t.name=...
....
访问结构体内的结构体属性(仍用“.”链接)
t.stu.name="马文";
t.stu.age=18;
....
————————————————————————————
结构体作函数参数
1.值传递
void printstudent(student s){
cout<<s.name<<.....;
}(主函数外)
printstudent(s);(主函数内)
特点:s的内容经过子函数操作后在主函数内仍为先前值(仅传递值)
2.地址传递
void printstudent(student *p){
cout<<p->name<<p->age<<.....;
}(主函数外)
printstudent(&s);(主函数内)
特点:s的内容若在子函数内被操作,则s的数值被切实改变
———若不想修改主函数内s的值,则用值传递;若希望通过子函数对s进行修改,则需用地址传递
——————————————————————————————————————
结构体中的const(设置只读防止误操作)
void printstudent(const student *p){
cout<<p->name<<p->age<<.....;
}
若设置只读后仍然试图操作该变量,将会报错如下
[Error] assignment of member 'student::age' in read-only object