c语言结构体作为形参是否加struct_结构体类型数据作为函数参数(三种方法)

(1)用结构体变量名作为参数。

#include

#include

using namespace std;

struct Student{

string name;

int score;

};

int main(){

Student one;

void Print(Student one);

one.name="千手";

one.score=99;

Print(one);

cout<

cout<

return 0;

}

void Print(Student one){

cout<

cout<

}

88cb1aff6fb3013d1432454175e87cb7.png

这种方式值采取的“值传递”的方式,将结构体变量所占的内存单元的内存全部顺序传递给形参。在函数调用期间形参也要占用内存单元。这种传递方式在空间和实践上开销较大,如果结构体的规模很大时,开销是很客观的。

并且,由于采用值传递的方式,如果在函数被执行期间改变了形参的值,该值不能反映到主调函数中的对应的实参,这往往不能满足使用要求。因此一般较少使用这种方法。

(2)用指向结构体变量的指针作为函数参数

#include

#include

using namespace std;

struct Student{

string name;

int score;

};

int main(){

Student one;

void Print(Student *p);

one.name="千手";

one.score=99;

Student *p=&one;

Print(p);

cout<

cout<

return 0;

}

void Print(Student *p){

cout<name<

cout<score<

}

28764ce0231656a97eaf2d9f6f22f104.png

这种方式虽然也是值传递的方式,但是这次传递的值却是指针。通过改变指针指向的结构体变量的值,可以间接改变实参的值。并且,在调用函数期间,仅仅建立了一个指针变量,大大的减小了系统的开销。

(3)用接头体变量的引用变量作函数参数

#include

#include

using namespace std;

struct Student{

string name;

int score;

};

int main(){

Student one;

void Print(Student &one);

one.name="千手";

one.score=99;

Print(one);

cout<

cout<

return 0;

}

void Print(Student &one){

cout<

cout<

}

28764ce0231656a97eaf2d9f6f22f104.png

实参是结构体变量,形参是对应的结构体类型的引用,虚实结合时传递的是地址,因而执行效率比较高。而且,与指针作为函数参数相比较,它看起来更加直观易懂。

因而,引用变量作为函数参数,它可以提高效率,而且保持程序良好的可读性。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值