int *b = new int();
const int *&a = b;
IDE 显示“int*
类型的表达式对const int*&
类型的引用的初始化无效”
我不明白。
最佳答案
你不能绑定(bind)不同类型的引用;对于这种情况,它们是 int *
和 const int*
。
对于const int *&a = b;
,b
是一个int*
,需要转换为const int *
首先。这里允许隐式转换,但是转换后的const int*
是临时的,不能绑定(bind)到a
;因为它是对非常量的左值引用。
另一方面,temporary object可以绑定(bind)到对 const 或右值引用的左值引用,即
const int * const &a = b; // fine, and the lifetime of the temporary is extended to match the lifetime of the reference a
注意 const
的位置,现在 a
被声明为指向 const int 的 const 指针的左值引用。
关于c++:从类型为 'const int*&' 的表达式对类型为 'int*' 的引用的初始化无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41874774/