[英]Why doesn't a reference to an array work until we use a pointer?
This works very well... 这非常有效......
int a[5] = {1,2,3,4,5}, int *p = a;
int *& ref = p;
But why doesn't this work? 但为什么这不起作用?
int a[5] = {1,2,3,4,5};
int*& ref = a;
Both a
and p
are pointers and have the same value (address of a[0]
). a
和p
都是指针并且具有相同的值( a[0]
地址)。 When I make reference to an array using a pointer ( p
), it works very well. 当我使用指针(
p
)引用数组时,它工作得很好。
But when I make reference to that array a[]
directly, it doesn't work... Why? 但是当我直接引用那个数组
a[]
,它不起作用......为什么?
a
is not a pointer, it is an array. a
不是指针,而是数组。 It has the type int[5]
. 它的类型为
int[5]
。 What it can do is decay to a pointer int*
, which is what happens in the first case. 它可以做的是衰减到指针
int*
,这是在第一种情况下发生的事情。 So, taking a reference to p
is ok. 所以,参考
p
是可以的。
Now for the second case. 现在是第二种情况。 Remember that
a
is not a pointer. 请记住,
a
不是指针。 So, there is an implicit conversion happening from int[5]
to int*
. 因此,从
int[5]
到int*
发生了隐式转换。 The result of that conversion is a prvalue. 转换的结果是prvalue。 But you can't bind a non-const lvalue reference (which is what
ref
is) to an rvalue! 但是你不能将一个非const左值引用(这是
ref
是什么)绑定到右值! So the code fails to compile. 所以代码无法编译。
Here's an analogy: 这是一个类比:
double a = 1.4;
int& b = a; // implicit conversion from 'double' to `int` results in prvalue
// and you can't bind non-const lvalue refs to rvalues.
int*& ref = a;
int*
is a pointer type, not an array type. int*
是指针类型,而不是数组类型。 So, that's why it won't bind to a
, which has type int[5]
. 所以,这就是为什么它不会绑定到具有
int[5]
类型的a
。
So, use const
所以,使用
const
int* const& ref = a;
It's works fine, Because the array name is an address constant, non-const reference can not refer to a constant. 它工作正常,因为数组名称是地址常量,非const引用不能引用常量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.