传递结构值与传递结构的引用
#include <iostream>
#include <cstring>
using namespace std;
struct Person
{
char name[20];
unsigned long id;
float salary;
};
Person allone[6] = {{"jone",12345,339.0},
{"david",13916,449.0},
{"marit",27519,311.0},
{"jasen",42876,623.0},
{"peter",23987,400.0},
{"yoke",12335,511.0}};
void print(Person pr)
{
cout<<pr.name<<" "
<<pr.id<<" "
<<pr.salary<<endl;
}
int main()
{
for(int i=0;i<6;i++)
print(allone[i]);
return 0;
}
输出结果为:
jone 12345 339
david 13916 449
marit 27519 311
jasen 42876 623
peter 23987 400
yoke 12335 511
可对上述代码的print函数改进,使用引用声明&,运行效率将提高,因为传引用不会产生值的备份。
返回结构
#include <iostream>
#include <cstring>
using namespace std;
struct Person
{
char name[20];
unsigned long id;
float salary;
};
void print(Person &pr)
{
cout<<pr.name<<" "
<<pr.id<<" "
<<pr.salary<<endl;
}
Person GetPerson()
{
Person temp;
cin>>temp.name>>temp.id>>temp.salary;
return temp;
}
int main()
{
Person Employee[3];
for(int i=0;i<3;i++)
{
Employee[i]=GetPerson();
print(Employee[i]);
}
return 0;
}
上述代码中,Getperson函数返回值的类型是Person。
事实上,无论是传递结构值,传递结构的引用还是返回结构,都可以这样去理解,定义结构之后,这种结构就是一种变量类型,所以和以往我们使用函数传递参数的方法和函数返回值都是一样的。例如,如果是函数返回值一个结构变量,那么设置该函数返回类型就是该结构的名称