库特 << 2[ "abc" ] << endl;为什么它有效?这是哪种语法?

cout << 2["abc"] << endl; why is it working? which syntax is it?

本文关键字:lt 语法 有效 endl abc 为什么 库特      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main(void) {
cout << 2["abc"] << endl;
return 0;
}
$ g++ test.cpp -o test
$ ./test
c

C++语法是什么?为什么它有效?有人能解释一下吗?

因为a[b]*(a + b)1并且b[a]*(b + a),并且+是可交换的。

1除非超载和其他恶作剧

数组索引是可变的。看看这个和这个。

在您的案例中,窄字符串文字基本上是字符的常量数组。哪个制造商:

cout << 2["abc"] << endl;

与相同

cout << "abc"[2] << endl;

部分引用(强调矿):

[lex.string/8]

。。。窄字符串文字的类型为"n const char的数组">。。。

[expr.sub/1]

后缀表达式后面跟一个方括号中的表达式是后缀表达式表达式之一应为类型的glvalue"T的数组">或类型为"指向T的指针"的prvalue,另一个应为非范围枚举的prvalue或积分类型。结果是类型为"T"。。。。


注意:它只适用于数组。当你这样做:

struct Foo
{
Foo& operator[](std::size_t index) { return *this; }
};
Foo foo;

以下将工作,因为它实际调用foo.operator[] (2)

Foo f;
f[2];    //Calls foo.operator[] (2);

以下内容将不起作用,因为其中一个表达式不是数组,因此编译器将继续查找合适的2.operator[] (foo),这将失败,因为积分类型没有成员函数。

2[f];   //will not work