一、定义与使用
struct student{
string name;
int score;
};
student s1;
s1.name = "xxx";
s1.score = 90;
student s2 = {"xxx", 90};
struct student{
string name;
int score;
}s3;
s3.name = "xxx";
s3.score = 90;
二、结构体数组
struct student{
string name;
int score;
};
student stuArray[3] =
{
{"A", 90},
{"B", 85},
{"C", 80}
};
stuArray[2].name = "D";
stuArray[2].score = 95;
for(int i = 0; i < 3; i++){
cout << "姓名: " << stuArray[i].name << "分数: " << stuArray[i].score << endl;
}
三、结构体指针
student s = { "A" , 18};
student *p = &s;
cout << "姓名: " << p->name << "分数: " << p->score << endl;
四、结构体嵌套
struct student{
string name;
int score;
};
struct teacher{
int id;
string name;
student stu;
};
teacher t;
t.id = 10000;
t.name = "haha";
t.stu.name = "lala";
t.stu.score = 90;
cout << t.name << t.id << t.stu.name << t.stu.score;
五、结构体做函数参数
void printStu1(student s){
cout << s.name << s.score;
}
void printStu2(student *p){
cout << p->name << p->score;
}
student s;
printStu2(&s);
六、结构体中const的使用场景
void printStu(const student *s)
{
cout << s->name << s->score;
}
student s;
printStu(&s);
|