c++ - 混淆的引用输出,如何分析?

标签 c++ reference

所以我不太明白引用是做什么的。我的家庭作业是给出以下代码的输出。但是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 = hb == 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?

引用不是对象,也没有地址。 hafoo .

So why is a == 1 in the output?

因为参数A afoo是来自 int a 的独立对象的 main功能。 H hfoo 中引用此局部变量而不是 main 中的那个.分配本地 int在一个函数内对另一个函数的局部变量没有影响。 amain 中初始化为 1并且该变量根本没有被修改。


c)

b is a reference, not?

是的。 bfoo 内是案例 c 的引用)。

Does that mean, that b's address is now the same as the address of a, meaning value of a == b?

同样,引用不是对象,也没有地址。 bfoobmain .


d)

h = reference of a so a has the same address like h? Then a has the name address as b?

同样,引用不是对象,也没有地址。 afooamain .

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?

同样,引用不是对象,也没有地址。引用afoo指的是amain作为参数给出,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不是引用。 bfoo指的是bmain , 和 aamain .

关于c++ - 混淆的引用输出,如何分析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312122/

相关文章:

rust - Rust 对临时值的不可变和可变引用是如何删除的?

c++ - C++ union 是如何知道其中存储的类型以及调用哪个析构函数的?

c++ - fstream 不写入文件

c++ - 在类构造函数中初始化结构

C++ 在 unique_ptr 的映射上迭代 std::accumulate():没有已知的转换

class - 使用类引用进行多态和继承(第2部分)?

php - 为什么当 PHP 数组的元素是引用分配时它会被修改?

c++ - 如何为 std::vector<std::vector<bool>> 编写哈希函数

C# 列出两个引用?

java - 多个重载方法 : Does null equal NullPointerException?