在C ++中是int [pointer-to-array]-标准吗? [英] is int[pointer-to-array] in the C++ - standard?

查看:77
本文介绍了在C ++中是int [pointer-to-array]-标准吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,可以编写以下代码:

As I have learned, one can write the following code:

char *a = new char[50];
for (int i = 0; i < 50; ++i) {
    i[a] = '5';
}

它会编译.有用.与

完全相同

It compiles. It works. It does exactly the same as

char *a = new char[50];
for (int i = 0; i < 50; ++i) {
    a[i] = '5';
}

是因为:

    默认情况下,
  • a[b]被实现为宏*(a + b),并且两个代码示例均有效,这只是偶然/编译器特有的
  • 它在某处是标准化的,并且在每个平台上,此类算法的结果应该相同
  • a[b] is implemented as a macro *(a + b) by default and the fact that both code samples are valid is just an accident/compiler specific
  • it's standardized somewhere and the outcome of such algorithms should be the same on every platform

合理地假设加法应该是可交换的,但是如果我们以这种方式实现operator[],则我们已经将其他东西进行了交换,这可能不是我们想要的.

It is reasonable to assume that addition should be commutative, but if we implement operator[] in that way, we have made something else commutative, what might not be what we wanted.

有趣的事实是,没有pointer[pointer]运算符,所以operator[]不是宏.

The interesting fact is that there is no pointer[pointer] operator, so operator[] is not a macro.

我知道这很糟糕.我知道这会使阅读代码的人感到困惑.但是我想知道这是否只是偶然的情况,并且在独角兽有七只脚和角在左脸的遥远土地上行不通.

I know it's bad. I know it's confusing the people who read the code. But I want to know if it's just an accident and it will not work in a distant land where unicorns have seven legs and horns are on their left cheek.

推荐答案

C ++标准,第8.3.4节,注释7(第185页)(重点是我的).

除已为类(13.5.5)声明的地方外,下标运算符[]的解释方式为E1[E2]*((E1)+(E2))相同.由于适用于+的转换规则,如果E1是数组,而E2是整数,则E1[E2]引用E1的第E2个成员.因此,尽管外观不对称,但下标是可交换的操作.

Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetric appearance, subscripting is a commutative operation.

这篇关于在C ++中是int [pointer-to-array]-标准吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆