gpt4 book ai didi

c++ - 无法理解代码片段的返回类型

转载 作者:太空宇宙 更新时间:2023-11-04 15:50:00 24 4
gpt4 key购买 nike

我很困惑为什么这个是对的。返回值为引用类型int&,但是 h() 函数返回一个值 int 类型在句子 return x 中。那么,如何将 int 返回更改为 int &

这是代码片段,使用 C++ 编译器可以很好地编译。

int& h() {
int q;
static int x;
return x;
}

最佳答案

这将返回对静态 int 的引用。 x 在第一次调用函数 h 时被初始化。像这样使用它:

int& href = h();
++href; // increments the static variable
int& href2 = h(); // another reference to the same static variable

变量 q 应该没有效果,我认为它是可疑的。

关于c++ - 无法理解代码片段的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10124042/

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