传递结构和结构成员函数 [英] Passing structures and structure members to functions

查看:144
本文介绍了传递结构和结构成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在传递结构功能将原型/头是什么样子?他们会是什么样传递结构的成员时功能,如?

When passing structures to functions what would the prototype / header look like? What would they look like when passing members of structures to functions?

例如...

struct a_struct{
int a;
int b;
};

a_struct point;

void f1(a_struct)
void f2(a_struct)

和让说,我想整个结构F1,而只是一个成员传递到F2。我将使用的数据类型a_struct作为参数两者兼而有之?或将F2具有不同的数据类型,因为我只是路过这是一个int成员。这是否会发生变化结构数组?我一直负责写程序是应该使用结构数组。我想这不会有太大的区别,只是它会被自动引用传递。

And lets say that I want to pass the whole structure to f1, but just a member to f2. Would I use the data type a_struct as parameter for both? Or would f2 have a different data type because I am only passing the member which is an int. Would this vary for an array of structures? The program I have been tasked to write is supposed to use arrays of structures. I figured that this wouldn't make much of a difference except that it will be passed by reference automatically.

推荐答案

在各地(不只是标量值)传递对象,你必须要担心内存的所有权和复制等,这意味着你有多么多种选择声明接口为您的功能。例如,您可以通过引用传递,或按值传递。

When passing objects around (not just scalar values), you have to be concerned about memory ownership and copying, etc. This means that you have multiple options for how you declare the interface for your function. For example, you can pass by reference or pass by value.

为你可能的声明可能是:

A possible declaration for you might be:

void f1(a_struct& struct);

这将传递给a_struct对象和prevent参考对象的任何拷贝。然而,你的榜样结构只包含标量值,所以复制对象的可能性不会引起过多的担心。其结果是,这将足以

This would pass a reference to the a_struct object and prevent any copying of the object. However, your example structure just contains scalar values, so the possibility of copying the object isn't cause for too much worry. As a result, this would suffice:

void f1(a_struct struct);

至于传递结构的成员成一个函数,该函数将需要宣告取构件的类型。例如,到a_struct的成员传递到一个函数,你会怎么做:

As far as passing a member of the struct into a function, the function would need to be declared to take the type of the member. For example, to pass the a member of the a_struct into a function, you would do:

void f1(int val);

最后,做阵列,因为他们会来作为一个函数指针复杂的事情。例如,通过a_struct对象的数组,你会作出这样的声明:

Finally, arrays do complicate things as they would come in as a pointer to the function. For example, to pass an array of a_struct objects, you would make this declaration:

void f1(a_struct* structs);

不过,您可以然后只需引用参数正常。例如:

However, you could then simply reference the parameter normally. For example:

structs[1];

这篇关于传递结构和结构成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆