gpt4 book ai didi

c++ - 引用似乎不变。为什么不在参数中?

转载 作者:行者123 更新时间:2023-11-30 01:24:01 24 4
gpt4 key购买 nike

测试一:

    #include <iostream>
void function(int &parameter);
int main()
{
int variableOne = 0;
int variableTwo = 6;
function(variableOne);
std::cout << variableOne << std::endl;
function(variableTwo);
std::cout << variableTwo << std::endl;
return 0;
}
void function(int &parameter) // ???
{
parameter += 5;
}

测试二:

    #include <iostream>
int main()
{
int variableOne = 2;
int variableThree = 7;
int &variableTwo = variableOne;
std::cout << variableOne << std::endl;
&variableTwo = variableThree; // ERROR (wrong side of operand etc...)
std::cout << variableThree << std::endl;
return 0;
}

1) 那么,为什么 &parameter 可以多次赋值(参数的),(测试一)而 &variableTwo (测试二)却不能?

2)这是因为,(测试一)参数的内存地址分配给了variableOne和variableTwo?或者,是否先将 variableOne 的值分配给参数,然后再分配给 variableTwo?

3)或许,是不是每次调用函数都会创建一个新的参数实例?

最佳答案

当您使用不同的参数调用 function 时,您将在每次调用时创建一个对该参数的新引用。

&variableTwo = variableThree;

在这里,您试图将 variableThree 的值分配给 variableTwo地址,这是非法的(并且不会感觉两者之一)。

此外,引用在创建后无法重新放置。因此,即使是以下内容也是非法的。

int &variableTwo = variableOne;
variableTwo = variableThree;

请注意,同样的规则也适用于函数。如果您尝试重新分配输入参数以引用其他某个整数,则代码将无法编译。

void function(int &parameter)
{
int local = 42;

parameter += 5;
parameter = local; // error!
}

关于c++ - 引用似乎不变。为什么不在参数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14216848/

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