gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:13:48 32 4
gpt4 key购买 nike

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

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com