c++:从类型为 'const int*&' 的表达式对类型为 'int*' 的引用的初始化无效

标签 c++ pointers reference initialization

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/

相关文章:

C++ - 为什么它有强大的异常保证?

c - 双向链表指针混淆

c++ - &a 的不同内容

c++ - 如何为所有者绘制对话框启用阴影

c++ - 重载 operator[] 的使用不明确

c++ - 在 C++ 中将二进制数据写入 fstream

c++ - 如何从将波兰表示法转换为反向波兰表示法的递归函数返回指针?

c - 指针、链表和函数

android - 使用 xml 引用字符串数组资源中的字符串

c++ - 在递归中使用按引用传递