【问题标题】:Why reference to array's object returns the object's address, not the value itself?为什么对数组对象的引用返回对象的地址,而不是值本身?
【发布时间】:2022-10-24 04:50:39
【问题描述】:

我研究数组已经有一段时间了,我很难理解这些代码行背后的想法:

int array[] {1, 2, 3, 4};
std::cout << "The address of the first element is " << &array[0];

为什么在这种情况下引用打印地址而不是值? 据我所知,引用访问被引用对象的值,而不是它的地址。

【问题讨论】:

  • 那不是参考 - 它是地址运算符
  • 表达式array[0] 产生对数组元素的引用(int&amp;)。在此引用上应用地址运算符(一元 &amp;)会生成指向此元素的指针(int*)

标签: c++ arrays reference


【解决方案1】:
int a = 24;
int& r = a; // <- when is part of a type (e.g `int&` here) `&` denotes a reference type

int* p = &a; // <- as an operator `&` is the address of operator

【讨论】:

    猜你喜欢
    • 2014-08-03
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 2021-06-29
    • 1970-01-01
    • 2010-09-13
    • 2020-01-10
    相关资源
    最近更新 更多