今晚看交流群的消息,看到大家在讨论一个有意思的问题:
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++中int数组与const指针引用的兼容性问题,解析了编译错误的原因,并提供了两种解决方案,深入理解const限定符在指针和引用中的作用。

8801

被折叠的 条评论
为什么被折叠?



