gpt4 book ai didi

c++ - 通过引用传递数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:22 33 4
gpt4 key购买 nike

如何通过引用传递静态分配的数组?

void foo(int (&myArray)[100])
{
}

int main()
{
int a[100];
foo(a);
}

(&myArray)[100] 是否有任何意义,或者它只是一种通过引用传递任何数组的语法?我不明白这里单独的括号后跟大括号。谢谢。

最佳答案

这是数组引用的语法 - 您需要使用 (&array) 向编译器阐明您想要对数组的引用,而不是(无效的)引用数组 int & array[100];.

编辑:一些说明。

void foo(int * x);
void foo(int x[100]);
void foo(int x[]);

这三种是声明同一个函数的不同方式。它们都被视为采用 int * 参数,您可以将任何大小的数组传递给它们。

void foo(int (&x)[100]);

这只接受 100 个整数的数组。您可以在 x

上安全地使用 sizeof
void foo(int & x[100]); // error

这被解析为“引用数组”——这是不合法的。

关于c++ - 通过引用传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39849260/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com