01结构体的定义和使用
#include<iostream>;
using namespace std;
#include<string>;
struct Student
{
string name;
int age;
int score;
};
int main(){
struct Student s1;
s1.name = "AISMALL_01";
s1.age = 18;
s1.score = 150;
cout << "姓名:" << s1.name << "年龄:" << s1.age << "分数:" << s1.score << endl;
struct Student s2 = { "AISMALL_02", 19, 150 };
cout << "姓名:" << s2.name << "年龄:" << s2.age << "分数:" << s2.score << endl;
struct Student1
{
string name;
int age;
int score;
}s3;
s3.name = "AISMALL_03";
s3.age = 20;
s3.score = 150;
cout << "姓名:" << s3.name << "年龄:" << s3.age << "分数:" << s3.score << endl;
system("pause");
return 0;
}
02结构体数组
#include<iostream>;
using namespace std;
#include<string>;
struct Student
{
string name;
int age;
int score;
};
int main(){
struct Student stuArray[3]=
{
{ "AISMALL_01", 18, 150 },
{ "AISMALL_02", 19, 150 },
{ "AISMALL_03", 20, 150 }
};
stuArray[1].age = 23;
for (int i = 0; i < 3; i++){
stuArray[i];
cout << "姓名:" << stuArray[i].name << "年龄:" << stuArray[i].age << "分数:" << stuArray[i].score << endl;
}
system("pause");
return 0;
}
03结构体指针
#include<iostream>;
using namespace std;
#include<string>;
struct Student
{
string name;
int age;
int score;
};
int main(){
struct Student s1 = { "AISMALL_01", 18, 150 };
struct Student s2 = { "AISMALL_02", 19, 150 };
struct Student s3 = { "AISMALL_03", 20, 150 };
struct Student *p;
p = &s1;
cout << "姓名:" << p->name << "年龄:" << p->age << "分数:" << p->score << endl;
system("pause");
return 0;
}
04结构体嵌套结构体
#include<iostream>;
using namespace std;
#include<string>;
struct Student
{
string name;
int age;
int score;
};
struct Teacher
{
int id;
string name;
int age;
struct Student stu;
};
int main(){
struct Teacher t1 = { 011, "dongdong", 38, { "AISMALL_01", 18, 150 } };
cout << "老师姓名:" << t1.name << "学生姓名:" << t1.stu.name << endl;
system("pause");
return 0;
}
05结构体做函数参数
#include<iostream>;
using namespace std;
#include<string>;
struct Student
{
string name;
int age;
int score;
};
void printStudent1(struct Student s){
s.age = 20;
cout << "子函数中 姓名:" << s.name << " 年龄:" << s.age << " 分数:" << s.score << endl;
}
void printStudent2(struct Student *s){
s->age = 22;
cout << "子函数中 姓名:" << s->name << " 年龄:" << s->age << " 分数:" << s->score << endl;
}
int main(){
struct Student s1 ={ "AISMALL_01", 18, 150 };
cout <<"未修改年龄的值:" << s1.age << endl;
printStudent1(s1);
cout << "值传递的子函数修改年龄后的值:" << s1.age << endl;
printStudent2(&s1);
cout << "地址传递的子函数修改年龄后的值:" << s1.age << endl;
system("pause");
return 0;
}
06结构体中的const使用
#include<iostream>;
using namespace std;
#include<string>;
struct Student
{
string name;
int age;
int score;
};
void printStudent1(const struct Student *s){
cout << "姓名:" << s->name << " 年龄:" << s->age << " 分数:" << s->score << endl;
}
int main(){
struct Student s1 = { "AISMALL_01", 18, 150 };
printStudent1(&s1);
system("pause");
return 0;
}