一,结构体用法
结构体为用户自定义的数据类型,放在主函数前,其定义方法如下:
struct Student{
string name;
int age;
int grade;
};
代码示例:
#include<iostream>
using namespace std;
#include<string>
struct Student{ /此处Student也可为student(不硬性要求大小写)
string name;
int age;
int grade;
}s3; /在此顺便创建
int main(){
/有三种常用创建结构体变量的方法:
/1.struct Student s1
struct Student s1;/此处Struct可省略(在创建结构体变量时可省略,但在定义结构体时不可省略)
s1.name="Tom";
s1.age=18;
s1.grade=100;
/2.struct Student s2={...}
struct Student s2={"Jerry",17,98};
/3.在创建结构体时创建
s3.name="park";
s3.age=20;
s3.grade=116;
system("pause");
return 0;
}
二,结构体数组
结构i示例:
struct student sa[3]={{x,x,x},{x,x,x},{x,x,x}};
代码示例:
#include<iostream>
using namespace std;
#include<string>
struct Student{
string name;
int age;
int grade;
};
int main(){
struct Student sa[3]={
{"Tomy",35,95},
{"Carl",28,90},
{"landy",48,88},
};
/也可重新赋值:
sa[2].name="David";
sa[2].age=27;
system("pause");
return 0;
}
三,结构体指针
定义指针:struct student *p=&s1;
访问变量:p->name/age/...
代码示例:
#include<iostream>
using namespace std;
#include<string>
struct Student{
string name;
int age;
int grade;
};
int main(){
struct Student s1={"Tom",18,140};
struct Student * p=&s1; /因为是自定义的类型,所以定义指针时也要用自定义的类型
cout<<p->name<<endl;
cout<<p->age<<endl;
cout<<p->grade<<endl; /通过->访问结构体变量属性
system("pause");
return 0;
}
四,结构体嵌套
j结构:
struct student{
string name;
int age;
int grade;
} ;
struct teacher{
string name;
int age;
struct student s1;
};
代码示例:
#include<iostream>
using namespace std;
#include<string>
struct student{ /因为teacher结构体中要用到student,所以student放前面
string name;
int age;
int grade;
};
struct teacher{
string name;
int age;
struct student s1;
};
int main(){
struct teacher t1;
t1.name="Tom";
t1.s1.name="Jerry";
system("pause");
return 0;
}
五,结构体做函数参数
同样分为两种方法:
1.值传递
2.地址传递
代码示例:
#include<iostream>
using namespace std;
#include<string>
struct student{
string name;
int age;
int score;
};
1.值传递
void printstudent1(struct student s){
cout<<s.name<<endl;
cout<<s.age<<endl;
cout<<s.score<<endl;
}
2.地址传递
void printstudent2(struct student * p){
cout<<p->name<<endl;
cout<<p->age<<endl;
cout<<p->score<<endl;
}
int main(){
struct student s={"Tom",17,128};
printstudent1(s);
printstudent2(&s);
system("pause");
return 0;
}
六,结构体中的const
非防止在地址传递下,使用函数时对数据产生误操作,可引入const。
代码示例:
#include<iostream>
using namespace std;
#include<string>
struct student{
string name;
int age;
int score;
};
void printstudent(const struct student * p){ 加入const使其转变为只读
cout<<p->name<<endl;
cout<<p->age<<endl;
cout<<p->score<<endl;
}
int main(){
struct student s={"Tom",17,128};
printstudent(&s);
system("pause");
return 0;
}