C++ error: non-const lvalue reference to type

今晚看交流群的消息,看到大家在讨论一个有意思的问题:

int array[5] = {
      0 };
int* const& p = array;  //编译通过
const int* &p = array; //编译失败
//报错: error: non-const lvalue reference to type 'const int *' 
//cannot bind to a value of unrelated type 'int [5]'。
//对类型“const int*”的非const左值引用不能绑定到不相关类型“int[5]的值 。

这话我看起来有点绕,好像说p不是const的,不能引用int[5]。仔细一想,诶嘿,有点道理。若p不是const,那么它是引用,那么它不就可以修改array(数组名)的值了么?

我想到两个解决办法:
(1)改为const int* const& p = array;
(2)改为const int* && p = array;

你可能感兴趣的:(C++语言)