结构体数组与指针:
结构体既然从属变量,那么便可以定义对应的数组与指针,方便对结构体的操作;作为函数参数,也是完全没有问题。
-
结构体数组:
struct Student { string name; int num; char sex; int age; }; Student stu[100]; //如此便定义出了100个学生的信息 //具体使用:(实现两个学生信息的录入与打印输出) #include<iostream> using namespace std; struct Student { string name; int num; char sex; int age; }; int main(int argc, char* argv[]) { Student stu[2]; //输入 for (int idx = 0; idx < 2; ++idx) { cin >> stu[idx].name; cin >> stu[idx].num; cin >> stu[idx].sex; cin >> stu[idx].age; } //输出 for (int idx = 0; idx < 2; ++idx) { cout << stu[idx].name << " " << stu[idx].num << " " << stu[idx].sex << " " << stu[idx].age << endl; } return 0; }
-
作为函数参数传递:默认情况下也是以值传递的方式
#include<iostream> using namespace std; struct Student //声明结构体 { string name; int num; char sex; int age; }; /* void set_num(Student stu) //设置学生的学号由101递增,但是该函数无法实现(原因是:采用默认的值传递) { static int stu_num = 101; stu.num = stu_num++; } */ void set_num(Student* pstu) //采用值传递的方法 { static int stu_num = 101; pstu->num = stu_num++; } int main(int argc, char* argv[]) { Student stu[2] = { { "aaa", 0, 'f', 10 }, { "bbb", 0, 'm', 12 } }; //遍历 for (int idx = 0; idx < 2; ++idx) { /* set_num(stu[idx]); //值传递 */ set_num(&stu[idx]); //地址传递 cout << stu[idx].name << " " << stu[idx].num << " " << stu[idx].sex << " " << stu[idx].age << endl; } return 0; }
-
结构体变量指针:
//解决办法1: Student stu; Student* pstu = &stu; (*pstu).num = 102; //这样好吗?(费时,费力,开销大) 这样不好 //升级: Student stu; Student* pstu = &stu; pstu->num = 102; //这样就好多了
在改写上述void set_num()函数时,已经体现了对结构体指针的使用:
将参数改成传递 Student* 指针的方式,一方面可以保证 set_num 函数可以修改外部的实参;另一方面又可以防止 Student 类型变量的拷贝工作,提高执行效率。(当前 Student 类型变量内部只有四个成员,可以说不多,但是在以后的编程过程中某个结构体或者类对象中可能包含几十个成员,这个时候如果进行拷贝的话开销可想而知。所以有时候即使不想在函数的内部修改实参的值,函数的参数类型也想定义成指针的类型就是这个目的。)
-
练习:
- 这句代码执行之后,到底是stu[0] 的 num 值变化了,还是 stu[1] 的 num 值变化了?
Student stu[2] =
{
{ "aaa", 0, 'f', 10 },
{ "bbb", 0, 'm', 12 }
};
Student* pstu = stu;
++pstu->num = 202;
结果:
- 定义一个学生类型的结构体,包含学生的:姓名、学号、分数。之后用该结构体定义大小为5的结构体变量数组。手动输入给数组成员赋值,之后将5个学生的信息输出出来,并且求出5个学生的分数的平均值也一起输出出来。