c++ - const int&和int&有什么区别

标签 c++ compiler-errors

我有3个问题。

1.两个代码之间有什么区别?

//why no errors during compiling as flowing
const int& get3() {
    return 3;
}


//get a compiler error, says: 'return': cannot convert from 'int' to 'int &'
//and that's understandable
int& get3() {
    return 3;
}

2.为什么第一个可以编译?

3.当我运行第一个时,我得到了奇怪的结果:

error image

这就是为什么?

如果有人可以给我一些提示,我将不胜感激。

最佳答案

使用int& get3(),您可以执行get3() = 5

这会将其引用由函数get3返回的变量的值设置为5

由于3是一个常量值,没有地址可用作引用,因此会出现编译错误。

此类函数通常返回对类成员变量的引用。

关于c++ - const int&和int&有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35570611/

相关文章:

c++ - 尝试调用方法: request for a member which is of a non-class type时出错

c++ - 创建队列类时出错

c++ - 在 QAbstractItemModel 中包装 QStringListModel 呈现一个空白列表

c++ - 是否可以在浏览器呈现之前拦截 http 请求并修改数据(例如使用正则表达式替换内容)?如果是这样,如何?

c# - 项目管理: Implementing custom errors in VS compilation process

ios - 将 ZIPArchive for iOS 添加到 xcode 时如何修复 'unknown type name' 错误

C++ 程序使终端崩溃——如何调试?

c++ - 将二进制字符串转换为 ASCII 字符串 (C++)

oracle - 获取此 oracle 错误消息 : PLS-00330: invalid use of type name or subtype name

java - 无法在 Java 中调用通用对象的方法