我们如何通过引用数组调用声明函数作为参数? [英] How can we declare the function with call by reference array as argument?

查看:72
本文介绍了我们如何通过引用数组调用声明函数作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑如何通过引用数组调用声明和调用函数作为参数。我写了一个代码,我得到一个错误,声明有关通过引用数组调用的函数。我怎么解决这个问题。



这是函数的声明:



I am confused how I can declare and call the function with call by reference array as argument. I wrote a code and I got an error for declaration of the function about call by reference array. How can I solve that.

This is a declaration of the function:

void lenEqualize(int &updDisStr2[], int shortLenStr[], int diffLen, int updLen);
// updDisStr2: is an array which should be called by reference
// shortLenStr: call by value array





调用函数:



call the function:

lenEqualize(updDisStr2[], equiDisStr2[], diffLen, updLen)

推荐答案

Quote:

void lenEqualize(int& updDisStr2 [],int shortLenStr [],int diffLen,int updLen);

void lenEqualize(int &updDisStr2[], int shortLenStr[], int diffLen, int updLen);



第一个参数是对 int 值的引用数组( [] 运算符绑定比& 一个,请参阅C ++运算符优先级 [ ^ ])。无论如何,我不明白为什么你应该通过引用传递数组?


First argument is an array of references to int values ( the [] operator binds tightly than the & one, see "C++ operator precedence"[^]). Anyway I don't get your point why should you pass an array by reference?


你似乎对如何引用数组感到困惑。声明为 int myints [5] 的数组只能通过其名称引用,没有前缀&符号,也没有后缀括号。我不确定按值数组调用是什么意思。

所以你的代码应该是这样的:

You seem to be confused about how to reference arrays. An array declared as int myints[5] can be referenced just by its name alone, no prefix ampersands and no suffix brackets. I'm not sure what you mean by call by value array.
So your code should be something like:

void lenEqualize(int* updDisStr2, int* shortLenStr, int diffLen, int updLen)
{
    // updDisStr2: is a pointer to an array
    // shortLenStr: is also a pointer to an array
}
//call the function:
int updDisStr2[10];
int shortLenStr[10];
int diffLen;
int updLen;
lenEqualize(updDisStr2, equiDisStr2, diffLen, updLen)</p>



请注意,函数参数中声明的名称是该函数的本地名称,并且不需要匹配原件。


Note that the names declared in the function parameters are local to that function and do not need to match the originals.


如果要传递引用并且大小和调用者必须具有已知大小的数组,则需要使用模板并添加缺少的括号。



为了灵活性,你应该使用std :: vector代替。



顺便说一句,你不能使用参考如果要在函数内创建新数组或将其大小变为chane,请使用语法。



虽然可以使用像解决方案2这样的指针来完成,但我建议使用像vector这样的STL容器。它的大小和数据保持在一起并且始终匹配,因此更易于维护。
You need to uses template and add missing parenthesis if you want to pass reference and have the size and the caller must have array with known size.

For flexibility, you should use std::vector instead.

By the way, you cannot use the reference syntax if you want to create a new array or chane its size inside the function.

Although it can be done with pointers using something like Solution 2, I would recommand to use STL containers like vector instead. It is much more maintainable as the size and the data are kept together and would always match.


这篇关于我们如何通过引用数组调用声明函数作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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