数组引用

// three equivalent definitions of printValues
void printValues(int*) { /* ... */ }
void printValues(int[]) { /* ... */ }
void printValues(int[10]) { /* ... */ }
等价,都是int*
编译器忽略为任何数组形参指定的长度。
// parameter treated as const int*, size of array is ignored
void printValues(const int ia[10])//这个10将被忽略
其他类型一样,数组形参可声明为数组的引用:
void printValues(int (&arr)[10]) { /* ... */ }
这个版本的 printValues 函数只严格地接受含有 10 个 int 型数值的数组,这限制了哪些数组可以传递。然而,由于形参是引用,在函数体中依赖数组的大小是安全的:

// ok: parameter is a reference to an array; size of array is fixed
void printValues(int (&arr)[10])
{
for (size_t i = 0; i != 10; ++i) {
cout << arr[i] << endl;
}
}
&arr 两边的圆括号是必需的,因为下标操作符具有更高的优先级:

f(int &arr[10]) // error: arr is an array of references
f(int (&arr)[10]) // ok: arr is a r

// initialize elements of an array to zero
     template <class T, size_t N> void array_init(T (&parm)[N])
     {
         for (size_t i = 0; i != N; ++i) {
             parm[i] = 0;
         }
     }

A template nontype parameter is a constant value inside the template definition. A nontype parameter can be used when constant expressions are requiredfor example, as we do hereto specify the size of an array.

模板非类型形参是模板定义内部的常量值,在需要常量表达式的时候,可使用非类型形参(例如,像这里所做的一样)指定数组的长度。

When array_init is called, the compiler figures out the value of the nontype parameter from the array argument:

当调用 array_init 时,编译器从数组实参计算非类型形参的值:

     int x[42];
double y[10];
array_init(x);  // instantiates array_init(int(&)[42]
array_init(y);  // instantiates array_init(double(&)[10]


 

posted @ 2009-01-26 18:07  米斯特刘  阅读(397)  评论(0编辑  收藏  举报