您现在的位置: 中国男护士网 >> 考试频道 >> 计算机等级 >> 二级辅导 >> C语言 >> 辅导 >> 正文    
  C/C++中的结构体(下) 【注册男护士专用博客】          

C/C++中的结构体(下)

www.nanhushi.com     佚名   不详 

下面我们重点对比两个例程,进一部分析关于效率的问题。

//-------------------------------------例程1---------------------------------

#include
#include
using namespace std;

struct test
{
char name[10];
float socre;
};

void print_score(test &pn)
{
cout<}

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{
a[i]=get_score();
}
cin.get();
for(int i=0;i{
print_score(a[i]);
}
cin.get();
} 来源:www.examda.com

//-------------------------------------例程2---------------------------------

#include
#include
using namespace std;

struct test
{
char name[10];
float socre;
};

void print_score(test &pn)
{
cout<}

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{
get_score(a[i]);
}
cin.get();
for(int i=0;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;
}
   却没有这一过程,不开辟任何新的内存空间,也没有任何临时变量的生成。

  第二:

  例程1在mian()中,必须对返回的结构体变量进行一次结构体变量与结构体变量直接的相互赋值操作。 for(int i=0;i{
a[i]=get_score();
}
   而例程2中由于是通过内存地址直接操作,所以完全没有这一过程,提高了效率。 for(int i=0;i{
get_score(a[i]);
}
   函数也是可以返回结构体应用的,例子如下:

#include
#include
using namespace std;

struct test
{
char name[10];
float socre;
};

test a;


test &get_score(test &pn)
{
cin>>pn.name>>pn.socre;
return pn;
}

void print_score(test &pn)
{
cout<} 来源:www.examda.com

void main()
{
test &sp=get_score(a);
cin.get();
cout<cin.get();
}
   调用get_score(a);结束并返回的时候,函数内部没有临时变量的产生,返回直接吧全局结构变量a的内存地址赋予结构引用sp

  最后提一下指针的引用

  定义指针的引用方法如下:

void main()
{
int a=0;
int b=10;
int *p1=&a;
int *p2=&b;
int *&pn=p1;
cout <pn=p2;
cout <cin.get();
}
   pn就是一个指向指针的引用,它也可以看做是指针别名,总之使用引用要特别注意它的特性,它的操作是和普通指针一样的,在函数中对全局指针的引用操作要十分小心,避免破坏全局指针!

 

文章录入:杜斌    责任编辑:杜斌 
  • 上一篇文章:

  • 下一篇文章:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
     

    联 系 信 息
    QQ:88236621
    电话:15853773350
    E-Mail:malenurse@163.com
    免费发布招聘信息
    做中国最专业男护士门户网站
    最 新 热 门
    最 新 推 荐
    相 关 文 章
    没有相关文章
    专 题 栏 目