结构体类型数据作为函数参数(三种⽅法)---转
将⼀个结构体变量中的数据传递给另⼀个函数,有下列3种⽅法:
1. ⽤结构体变量名作参数。⼀般较少⽤这种⽅法。
2. ⽤指向结构体变量的指针作实参,将结构体变量的地址传给形参。
3. ⽤结构体变量的引⽤变量作函数参数。
下⾯通过⼀个简单的例⼦来说明,并对它们进⾏⽐较。
有⼀个结构体变量stu,内含学⽣学号、姓名和3门课的成绩。要求在main函数中为各成员赋值,在另⼀函数print中将它们的值输出。
1) ⽤结构体变量作函数参数。
1 #include <iostream>
2 #include <string>
3using namespace std;
4struct Student//声明结构体类型Student
5 {
6int num;
7char name[20];
8float score[3];
9 };
10int main( )
11 {
12void print(Student); //函数声明,形参类型为结构体Student
13    Student stu; //定义结构体变量
14    stu.num=12345; //以下5⾏对结构体变量各成员赋值
15    stu.name="Li Fung";
16    stu.score[0]=67.5;
17    stu.score[1]=89;
18    stu.score[2]=78.5;
19    print(stu); //调⽤print函数,输出stu各成员的值
20return0;
21 }
22void print(Student st)
23 {
24    cout<<st.num<<""<<st.name<<""<<st.score[0]
25    <<"" <<st.score[1]<<""<<st.score[2]<<endl;
26 }
2)⽤指向结构体变量的指针作实参在上⾯程序的基础上稍作修改即可。
1 #include <iostream>
2 #include <string>
3using namespace std;
4struct Student
5 {
6int num; string name; //⽤string类型定义字符串变量
7float score[3];
8 }stu={12345,"Li Fung",67.5,89,78.5}; //定义结构体student变量stu并赋初值
9int main( )
10 {
11void print(Student *); //函数声明,形参为指向Student类型数据的指针变量
12    Student *pt=&stu; //定义基类型为Student的指针变量pt,并指向stu
13    print(pt); //实参为指向Student类数据的指针变量
14return0;
结构体数组不能作为参数传递给函数
15 }
16
17//定义函数,形参p是基类型为Student的指针变量
18void print(Student *p)
19 {
20    cout<<p->num<<""<<p->name<<""<<p->score[0]<<"" <<
21    p->score[1]<<""<<p->score[2]<<endl;
22 }
调⽤print函数时,实参指针变量pt将stu的起始地址传送给形参p(p也是基类型为student的指针变量)。这样形参p 也就指向stu
在print函数中输出p所指向的结构体变量的各个成员值,它们也就是stu的成员值。在main函数中也可以不定义指针变量pt,⽽在调⽤print函数时以&stu作为实参,把stu的起始地址传给实参p。
3) ⽤结构体变量的引⽤作函数参数
1 #include <iostream>
2 #include <string>
3using namespace std;
4struct Student
5 {
6int num;
7string name;
8float score[3];
9 }stu={12345,"Li Li",67.5,89,78.5};
10
11int main( )
12 {
13void print(Student &);
14//函数声明,形参为Student类型变量的引⽤
15    print(stu);
16//实参为结构体Student变量
17return0;
18 }
19
20//函数定义,形参为结构体Student变量的引⽤
21void print(Student &stud)
22 {
23    cout<<stud.num<<""<<stud.name<<""<<stud.score[0]
24    <<"" <<stud.score[1]<<""<<stud.score[2]<<endl;
25 }
程序(1)⽤结构体变量作实参和形参,程序直观易懂,效率是不⾼的。
程序(2)采⽤指针变量作为实参和形参,空间和时间的开销都很⼩,效率较⾼。但程序(2)不如程序(1)那样直接。
程序(3)的实参是结构体Student类型变量,⽽形参⽤Student类型的引⽤,虚实结合时传递的
是stu的地址,因⽽效率较⾼。它兼有(1)和(2)的优点。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。