定义通过指针访问结构体中的成员
利用->可以通过结构体指针访问结构体属性
struct student s = { "张",16,66 };
struct student *p = &s; //这里不要用int *p,因为s的类型为student,struct可省略。这里指针p指向的s这个变量的地址
cout << p->name << p->age <<endl; //相当于一般的指针的解引用,*p不适用
2 ,结构体嵌套结构体
比如老师手底下有2个学生
struct teacher
{
int id;
string name;
int age;
struct student stu; //在老师结构体中创建学生变量,student 是数据类型,stu是变量名
}
struct student
{
string name;
int age;
int score;
};
struct teacher
{
string name;
struct student stu[2]; //也可以放一个数组
};
int main()
{
struct teacher t;
t.name = "张丹";
t.stu[0].name = "阿萨德";
t.stu[0].age = 43;
t.stu[0].score = 423;
t.stu[1].name = "萨德";
t.stu[1].age = 3;
t.stu[1].score = 23;
for (int i = 0; i < 2; i++)
{
cout << t.stu[i].name << t.stu[i].age << t.stu[i].score << endl;
}
system("pause");
return 0;
}
3,结构体作函数参数
值传递,地址传递
结构体嵌套数组结构体,并用指针修改了实参的例子
struct student
{
string name;
int age;
int score;
};
struct teacher
{
string name;
struct student stu[3];
};
void zhi(struct teacher t) //因为stu的变量已在main函数赋值,这里就不用在赋值。
//t.stu[0].name,t.name也可以放在这里
{
for (int i = 0; i < 2; i++)
{
cout << "值传递" << t.stu[i].name << " " << t.stu[i].age << " " << t.stu[i].score << endl;
}
}
void address(struct teacher *p) //结构体嵌套数组结构体的地址传递,其中的解引用必须是
{ //子函数定义的指针p解引用->子结构体,
//子结构体再用.访问子结构体中的值,括号代表这是个值
if ((p->stu[0].age) > 20)
{
p->stu[0].name = "阿道夫"; //这里与类有关
}
for (int i = 0; i < 2; i++)
{
cout << "地址传递" << (p->stu[0].name) << " " << (p->stu[0].age) << " " << (p->stu[0].score) << endl;
}
}
int main()
{
struct teacher t;
t.name = "张丹";
t.stu[0].name = "阿萨德";
t.stu[0].age = 43;
t.stu[0].score = 423;
t.stu[1].name = "萨德";
t.stu[1].age = 3;
t.stu[1].score = 23;
zhi(t); //值传递结构体,因为stu在teacher结构体中,所以只用传送teacher定义的变量即可
address(&t); //地址传递结构体,传送的t的地址
for (int i = 0; i < 2; i++)
{
cout << "改变后的初值" << t.stu[i].name << " " << t.stu[i].age << " " << t.stu[i].score << endl;
}
system("pause");
return 0;
}
4,const
用const防止误操作
值传递锁传输的数据量较大,所以用地址传递比较节省内存空间,但指针修改值后,整体的值都要变。所以加const,使指针不能修改
void address(const struct teacher *p) //有了const后就不能在子函数里修改数值
{//(p->stu[0].name) = "法师"; 因为加了const
for (int i = 0; i < 2; i++)
{
cout << "地址传递" << (p->stu[0].name) << " " << (p->stu[0].age) << " " << (p->stu[0].score) << endl;
}
}