被引用变量的内存位置是什么?

What is the memory location of referenced variables?

本文关键字:位置 是什么 内存 引用 变量      更新时间:2023-10-16
int main()
{
  int i = 10;
  int &j = i;
  int k = 20;
  j=k;
  cout << i << j << k;
  return 0;
}

上述程序的输出为202020.

在上面的代码片段中,i和j的内存位置是什么?它们的内存位置是相同的还是不同的?

j是对i的引用,所以当你改变j的值时,它的值也会改变。

你可能需要做更多的学习,以便将来你能弄清楚这些事情,但让我们来看看你的程序:

  int i = 10;  //Makes an int with value 10
  int &j = i;  //Makes a reference which points to i
  int k = 20;  //Makes an int with value 20
  j=k;         //You are making the reference the area that 
               //j represents (ie. i) the same as k
  cout << i << j << k;  //j = 20 therefore i = 20

希望有帮助。

int i = 10;

i已经在堆栈上被分配,其地址指向值10。

int &j = i;

j在栈上已经被分配了,它的地址被分配给i的地址,i的地址指向值10。此时i和j的地址是相同的

int k = 20;

k已经在栈上被分配,其地址指向值20。

j=k;

地址j的值已经赋给地址k的值(20)。

此时,i和j有相同的地址,其值为20。

k有不同的地址,但k的地址值也是20