c + +通过引用传递数组 [英] C++ pass an array by reference
问题描述
这是允许按引用传递数组?
is this allowed to pass an array by reference ?
void foo(double& *bar)
看来,我的编译器说,没有。为什么?什么是按引用传递数组的正确方法?或周围的工作?我有我的方法应该修改,我应该事后检索数组参数。或者,我可以让这个数组类的成员,它工作得很好,但它对于我的code的另一部分(即我想避免)。
Seems that my compiler says no. Why? What is the proper way to pass an array by reference? Or a work around? I have an array argument that my method should modify and that I should retrieve afterwards. Alternatively, I could make this array a class member, which works fine, but it has many drawbacks for other part of my code (that I would like to avoid).
感谢和问候。
推荐答案
数组只能通过引用传递,实际上是:
Arrays can only be passed by reference, actually:
void foo(double (&bar)[10])
{
}
这prevents你做这样的事情:
This prevents you from doing things like:
double arr[20];
foo(arr); // won't compile
要能够为任意大小的数组传递给富
,使它成为一个模板,并捕获在编译时数组的大小:
To be able to pass an arbitrary size array to foo
, make it a template and capture the size of the array at compile time:
template<typename T, size_t N>
void foo(T (&bar)[N])
{
// use N here
}
您应该认真考虑使用的std ::矢量
,或者如果你有一个支持C ++ 11,的std ::阵列编译器
。
You should seriously consider using std::vector
, or if you have a compiler that supports c++11, std::array
.
这篇关于c + +通过引用传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!