gpt4 book ai didi

c++ - 向左值引用分配右值

转载 作者:行者123 更新时间:2023-12-01 14:42:48 25 4
gpt4 key购买 nike

我正在看有关rvalues和lvalues的教程,我有些困惑。

int& GetValue()
{
static int value = 5;
return value;
}

int main()
{
int a = GetValue();

GetValue() = 8;

std::cout << a << std::endl;
std::cout << GetValue() << std::endl;

int b = GetValue();
std::cout << b << std::endl;
return 0;
}


此打印
5
8
8

我不明白 GetValue() = 8;如何将值从5更改为8。现在,当您调用 GetValue()时,我总是得到8。

最佳答案

astaticGetValue()变量的副本:

int a = GetValue();

因此,以后的作业:
GetValue() = 8;

不会影响 a的值。但是,它确实修改了静态变量 value的值,该值随后被检索两次:
  • std::cout << GetValue() << std::endl;
  • int b = GetValue();
  • 关于c++ - 向左值引用分配右值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62023923/

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