上面我们说明了易用引用对结构体进行操作的优势,下面我们重点对比两个例程,进一部分析关于效率的问题。
//程序作者:管宁
//站点:www.cndev-lab.com
//所有稿件均有版权,如要转载,请务必著名出处和作者
//-------------------------------------例程1---------------------------------
#include <iostream>
#include <string>
using namespace std;
struct test
{
char name[10];
float socre;
};
void print_score(test &pn)
{
cout<<pn.name<<"|"<<pn.socre<<endl;
}
test get_score()
{
test pn;
cin>>pn.name>>pn.socre;
return pn;
}
void main()
{
test a[2];
int num = sizeof(a)/sizeof(test);
for(int i=0;i<num;i++)
{
a[i]=get_score();
}
cin.get();
for(int i=0;i<num;i++)
{
print_score(a[i]);
}
cin.get();
}
//-------------------------------------例程2---------------------------------
#include <iostream>
#include <string>
using namespace std;
struct test
{
char name[10];
float socre;
};
void print_score(test &pn)
{
cout<<pn.name<<"|"<<pn.socre<<endl;
}
void get_score(test &pn)
{
cin>>pn.name>>pn.socre;
}
void main()
{
test a[2];
int num = sizeof(a)/sizeof(test);
for(int i=0;i<num;i++)
{
get_score(a[i]);
}
cin.get();
for(int i=0;i<num;i++)
{
print_score(a[i]);
}
cin.get();
}
例程2的效率要远高过例程1的原因主要有以下两处:
第一:
例程1中的
test get_score()
{
test pn;
cin>>pn.name>>pn.socre;
return pn;
}
调用的时候在内部要在栈空间开辟一个名为pn的结构体变量,程序pn的时候又再次在栈内存空间内自动生成了一个临时结构体变量temp,在前面的教程中我们已经说过,它是一个copy,而例程2中的:
void get_score(test &pn)
{
cin>>pn.name>>pn.socre;
}
却没有这一过程,不开辟任何新的内存空间,也没有任何临时变量的生成。