库特 << 2[ "abc" ] << endl;为什么它有效?这是哪种语法?
cout << 2["abc"] << endl; why is it working? which syntax is it?
#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
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- <<操作员在下面的行中工作
- 单独定义模板化嵌套类方法的正确语法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 为什么我会收到错误 C2143 语法错误:缺少"*"之前的';'?
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 使用基类指针调用基类的值构造函数的语法是什么?
- 很好的语法来获取对向量/数组数据的大小引用?
- C++语法运算符功能?
- 重载运算符<<用于ostream语法