我有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/