电脑爱好者,提供IT资讯信息及各类编程知识文章介绍,欢迎大家来本站学习电脑知识。 最近更新 | 联系我们 RSS订阅本站最新文章
电脑爱好者
站内搜索: 
当前位置:首页>> C++/VC>>新手入门:C/C++中的结构体之二:

新手入门:C/C++中的结构体之二

来源:远方网络 | 2006-1-6 | (有2320人读过)

下面我们来看一下,结构体变量是如何作为函数参数进行传递的。

#include<iostream>

#include<string>

usingnamespacestd;

structtest

{

charname[10];

floatsocre;

};

voidprint_score(testpn)//以结构变量进行传递

{

cout<<pn.name<<"|"<<pn.socre<<endl;

}

voidprint_score(test*pn)//一结构指针作为形参

{

cout<<pn->name<<"|"<<pn->socre<<endl;

}

voidmain()

{

testa[2]={{"marry",88.5},{"jarck",98.5}};

intnum=sizeof(a)/sizeof(test);

for(inti=0;i<num;i++)

{

print_score(a[i]);

}

for(inti=0;i<num;i++)

{

print_score(&a[i]);

}

cin.get();

}

void print_score(test *pn)的效率是要高过void print_score(test pn)的,因为直接内存操作避免了栈空间开辟结构变量空间需求,节省内存。

下面我们再说一下,传递结构引用的例子。

利用引用传递的好处很多,它的效率和指针相差无几,但引用的操作方式和值传递几乎一样,种种优势都说明善用引用可以做到程序的易读和易操作,它的优势尤其在结构和大的时候,避免传递结构变量很大的值,节省内存,提高效率。

#include<iostream>

#include<string>

usingnamespacestd;

structtest

{

charname[10];

floatsocre;

};

voidprint_score(test&pn)//以结构变量进行传递

{

cout<<pn.name<<"|"<<pn.socre<<endl;

}

voidmain()

{

testa[2]={{"marry",88.5},{"jarck",98.5}};

intnum=sizeof(a)/sizeof(test);

for(inti=0;i<num;i++)

{

print_score(a[i]);

}

cin.get();

}

C++/VC热门文章排行
网站赞助商
购买此位置

 

关于我们 | 网站地图 | 文档一览 | 友情链接| 联系我们

Copyright © 2003-2024 电脑爱好者 版权所有 备案号:鲁ICP备09059398号