为什么对变量的引用有时表现为大小为 1 的数组?
Why does a reference to a variable behave as an array of size 1 sometimes?
#include <iostream>
using namespace std;
void outputFirst(int x[]) {
cout << x[0] << endl;
}
int main() {
int x = 40;
// works
outputFirst(&x);
// works
int *y = &x;
cout << y[0] << endl;
// invalid types ‘int[int]’ for array subscript
cout << &x[0] << endl;
return 0;
}
当我将它传递给函数或先将其分配给另一个变量时,为什么我可以将对 int 的引用用作数组,而不是直接使用?
我正在使用 g++-6.3。
Why can I use a reference to an int
请注意,&x
并不意味着引用 x
,它意味着 taking the address of x
,您将得到一个指针(即 int*
) 从中。所以 int *y = &x;
表示从 x
中获取地址,然后 y[0]
表示获取指针指向的数组的第一个元素(就好像它指向数组的第一个元素只包含一个元素(即 x
) ),所以最后它 returns x
本身。
关于为什么 &x[0]
不起作用,请注意 operator[]
的 precedence 高于 operator&
。然后 &x[0]
被解释为 &(x[0])
,而 x[0]
无效,因为 x
只是一个 int
.
您应该添加括号以明确指定优先级,例如
cout << (&x)[0] << endl;
#include <iostream>
using namespace std;
void outputFirst(int x[]) {
cout << x[0] << endl;
}
int main() {
int x = 40;
// works
outputFirst(&x);
// works
int *y = &x;
cout << y[0] << endl;
// invalid types ‘int[int]’ for array subscript
cout << &x[0] << endl;
return 0;
}
当我将它传递给函数或先将其分配给另一个变量时,为什么我可以将对 int 的引用用作数组,而不是直接使用?
我正在使用 g++-6.3。
Why can I use a reference to an int
请注意,&x
并不意味着引用 x
,它意味着 taking the address of x
,您将得到一个指针(即 int*
) 从中。所以 int *y = &x;
表示从 x
中获取地址,然后 y[0]
表示获取指针指向的数组的第一个元素(就好像它指向数组的第一个元素只包含一个元素(即 x
) ),所以最后它 returns x
本身。
关于为什么 &x[0]
不起作用,请注意 operator[]
的 precedence 高于 operator&
。然后 &x[0]
被解释为 &(x[0])
,而 x[0]
无效,因为 x
只是一个 int
.
您应该添加括号以明确指定优先级,例如
cout << (&x)[0] << endl;