C++ 通过引用传递数组 [英] C++ pass an array by reference
问题描述
这是否允许通过引用传递数组?
is this allowed to pass an array by reference ?
void foo(double& *bar)
似乎我的编译器说不.为什么?通过引用传递数组的正确方法是什么?还是变通?我有一个数组参数,我的方法应该修改它,然后我应该检索它.或者,我可以让这个数组成为一个类成员,这很好用,但它对我的代码的其他部分有很多缺点(我想避免).
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])
{
}
这会阻止您执行以下操作:
This prevents you from doing things like:
double arr[20];
foo(arr); // won't compile
为了能够将任意大小的数组传递给foo
,将其设为模板并在编译时捕获数组的大小:
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::vector
,或者如果你有一个支持c++11的编译器,std::array
.
You should seriously consider using std::vector
, or if you have a compiler that supports c++11, std::array
.
这篇关于C++ 通过引用传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!