下面这两个函数test1和test2有什么区别吗
static int const MAXL = 3;
void test1(int t[MAXL])
{
for (int i = 0; i < MAXL; ++i)
t[i] = 10;
}
void test2(int (&t)[MAXL])
{
for (int i = 0; i < MAXL; ++i)
t[i] = 10;
}通过我在MSVC2008中的测试,这两个函数都修改了输入数组值。看起来这两个函数在功能上是相同的。
有没有人能给出一个需要在函数参数中引用数组的例子?
发布于 2013-07-10 11:33:46
第一个衰减为指向数组中第一个元素的指针,第二个是对数组的实际引用。
它们是不同的,就像指针和引用通常是不同的。
具体地说,在数组的情况下,对数组的引用非常有用,因为您可以保留确定数组大小的能力。这使您不必像在C API中那样将数组的大小/长度作为单独的参数进行传递。
实现这一点的一种方式,我认为是特别巧妙的,涉及模板。使用模板参数,您可以让编译器自动推断数组的大小。例如:
void ProcessArray(int* pArray, std::size length)
{
for (std::size_t i = 0; i < length; ++i)
{
// do something with each element in array
}
}
template <std::size_t N>
void ProcessArray(int (&array)[N])
{
ProcessArray(array, N); // (dispatch to non-template function)
}https://stackoverflow.com/questions/17562026
复制相似问题