是否由ref或值默认传递数组? 感谢。

有帮助吗?

解决方案

它们被作为指针传递。这意味着,关于数组大小的所有信息都将丢失。你会好得多建议使用std ::载体,它可以通过值或引用传递,任你选择,因此保留其所有的信息。

下面是将数组传递给函数的一个例子。注意,我们必须专门指定元件的数量,如的sizeof(P)将使指针的大小。

int add( int * p, int n ) {
   int total = 0;
   for ( int i = 0; i < n; i++ ) {
       total += p[i];
   }
   return total;
}


int main() {
    int a[] = { 1, 7, 42 };
    int n = add( a, 3 );
}

其他提示

首先,你不能在这个意义上,所述阵列的副本是由通过值的阵列。如果你需要的功能,使用std::vectorboost::array

一般情况下,一个指针到所述第一元件由值来传递。阵列的大小是失去了在这个过程中,必须单独通过。下面签名都是等效的:

void by_pointer(int *p, int size);
void by_pointer(int p[], int size);
void by_pointer(int p[7], int size);   // the 7 is ignored in this context!

如果你想通过引用传递,大小是类型的一部分:

void by_reference(int (&a)[7]);   // only arrays of size 7 can be passed here!

通常你通过与模板结合参考通,所以可以使用具有不同静态已知尺寸功能:

template<size_t size>
void by_reference(int (&a)[size]);

希望这有助于。

数组是特殊:它们总是作为指针到所述阵列的所述第一元件传递

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top