所以我不太明白引用是做什么的。我的家庭作业是给出以下代码的输出。但是A,B,H总是从being and int变成int&。
a) A = int, B = int, H = int
b) A = int, B = int, H = int&
c) A = int, B = int&, H = int
d) A = int&, B = int, H = int
e) A = int&, B = int, H = int&
f) A = int&, B = int&, H = int
#include<iostream>
int foo (A a, B b)
{
H h = a; a = b;
b = h; return h;
}
int main()
{
int a = 1;
int b = 2;
int r = foo (a, b);
std::cout << a << " " << b << " " << r;
return 0;
}
因此,a) 显然不是问题。但是已经 b) 让我感到困惑。
对于b); int& h = a
是把h的地址设置成a的地址?所以h == Adresse of a
,意思是h == a
的值。然后 a = b
(其中 b == 2)使得 a == b == h == 2
,那么为什么 a == 1
在输出中?
对于c); h == 1
很清楚,但是 a = b
这行我觉得很困惑。 b 是引用,不是吗?这是否意味着 b 的地址现在与 a 的地址相同,即 a == b
的值?我猜我的想法是正确的,因为我得到了正确的输出。
对于d); h = a 的引用
那么 a 和 h 有相同的地址吗?那么a的名称地址为b?所以 a == b == 2
。但现在对我来说是奇怪的部分。 b = h
但 b == 2
,所以 2 = h
,但这不是与 L/R - 值冲突吗?为什么 h 现在是 1?
对于e);没有线索,int& h ?= int& a,这里发生了什么? h 和 a 有相同的地址吗?那么a的地址现在是b?所以地址是2?那么b持有h的地址?
对于f);首先,h 现在有 a 的地址,所以 h == a
。那么a和b有相同的地址。那么b的地址就和h一样了。正确的想法?
解决方案是
a) 1 2 1
b) 1 2 2
c) 1 1 1
d) 2 2 1
e) 2 2 2
f) 2 1 1
我特别需要 b) 和 e) 方面的帮助,非常感谢,对于冗长的文本感到抱歉。
最佳答案
二)
for b); int& h = a is setting h's address to a's address?
引用不是对象,也没有地址。 h
指a
的 foo
.
So why is a == 1 in the output?
因为参数A a
的 foo
是来自 int a
的独立对象的 main
功能。 H h
在 foo
中引用此局部变量而不是 main
中的那个.分配本地 int
在一个函数内对另一个函数的局部变量没有影响。 a
在 main
中初始化为 1并且该变量根本没有被修改。
c)
b is a reference, not?
是的。 b
在 foo
内是案例 c 的引用)。
Does that mean, that b's address is now the same as the address of a, meaning value of a == b?
同样,引用不是对象,也没有地址。 b
在foo
指b
在main
.
d)
h = reference of a so a has the same address like h? Then a has the name address as b?
同样,引用不是对象,也没有地址。 a
在foo
指a
在main
.
And why is h now 1?
因为这是它在 foo
中初始化的内容.
e)
no clue, int& h ?= int& a, what happens here? h and a have the same address? Then the address of a is now b? So the address is 2? Then b holds the address of h?
同样,引用不是对象,也没有地址。引用a
在foo
指的是a
在main
作为参数给出,h
指的是同一个对象。 b
不是引用。
d)
First, h has now the address of a, so h == a. Then a has the same address as b. Then the address of b is the same as h.
h
不是引用。 b
在foo
指的是b
在main
, 和 a
指a
在main
.
关于c++ - 混淆的引用输出,如何分析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312122/