关于数组的 C++ 问题

标签 c++ c++11 include

<分区>

任何人都可以向我解释为什么这是可能的吗?。 我知道 a 与 &a[0] 相同,例如我也明白 *(a+1) 是第二个元素,我可以使用 *((a+i)+j) 技术,但我一生中第一次看到这样的代码,现在我很困惑。 我知道输出是数组的第四个元素。但是谁能向我解释为什么这是可能的?

#include<iostream>
int a[] = {1,2,3,4,5};
std::cout << (3)[a] << std::endl; 

最佳答案

二进制表达式:

x[y]

被定义为等于:

*(x+y)

(在没有 operator [] 重载的情况下)。

3+aa+3 相同,所以 3[a]a[3] 相同

3+a 的上下文中,数组 a 的名称衰减为指向其第一个元素的指针,因此我们尝试添加一个指针和一个整数使用内置的加法运算符。 The latest draft of C++14在第 5.7 节 [expr.add] 第 4 段中说:

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist

这与 C++14 标准的文本非常接近,但这种行为自 C89 以来一直稳定(实际上自 70 年代的 BCPL 以来)。

话虽如此,如果您找到这样的代码,请找到作者并用线索 Racket 打他的脑袋。编写 C++ 非常容易,没有人(包括一周后的你自己)可以阅读 - 这对任何人都没有用。

关于关于数组的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292114/

相关文章:

c# - "Speech bubble"通知

c# - 您如何通过 WiFi 或 LAN 网络在不同的机器上验证 Windows 用户凭据?

我们可以使用头文件而不指定其 .h 扩展名吗

php - PHP包含文件中的 undefined variable 错误

html - .inc 文件未可靠包含

c++ - 避免使用辅助函数进行比较

c++ - 为什么openCV中的输入图像findContours()要转灰度?

c++ - 尝试将 std::vector<std::pair<T, U>> 转换为其左值 ref 时收到 VS 编译器警告 C4239

c++ - 使用数据数组调用函数时的模板参数包扩展

c++ - 从模板类多重继承