为什么我可以在运算符+ =的右侧使用初始化程序列表,但不能在运算符+的右侧使用初始化程序列表? [英] Why can I use initializer lists on the right-hand side of operator += but not operator+?
问题描述
这是对这个较早的问题.
请考虑以下C ++代码,您可以在ideone.com上直播
Consider the following C++ code, which you can try live at ideone.com:
#include <iostream>
#include <initializer_list>
using namespace std;
struct AddInitializerList {
void operator+= (initializer_list<int> values) {
// Do nothing
}
void operator+ (initializer_list<int> values) {
// Do nothing
}
};
int main() {
AddInitializerList adder;
adder += {1, 2, 3}; // Totally legit
adder + {1, 2, 3}; // Not okay!
return 0;
}
main
中将operator+
与大括号括起来的初始化程序列表一起使用的行不会编译(并且,在问了前面的问题之后,我现在知道这是为什么).但是,我很困惑为什么在main
中使用opeartor+=
的代码确实可以很好地编译.
The line in main
that uses operator+
with a brace-enclosed initializer list does not compile (and, after asking that earlier question, I now know why this is). However, I'm confused why the code that uses opeartor+=
in main
does indeed compile just fine.
我对为什么可以重载+=
并使它正常工作感到困惑,而重载+
似乎在这里不起作用.标准中是否有特定规定允许在+=
运算符而不是+
运算符的上下文中使用大括号括起来的初始化程序?还是这只是一个奇怪的编译器怪癖?
I'm confused as to precisely why I can overload +=
and have it work just fine, while overloading +
doesn't seem to work here. Is there a particular provision in the standard that permits brace-enclosed initializers in the context of the +=
operator but not the +
operator? Or is this just a weird compiler quirk?
推荐答案
It is explained in the answer to this question (which is linked from the question you linked to).
语言语法仅在特定的语法环境中允许使用括号列表,而不是任意表达式.该列表包括赋值运算符的右侧,但通常不包括运算符的右侧.
The language grammar only allows a braced list in certain grammatical contexts, not in place of an arbitrary expression. That list includes the right-hand side of assignment operators, but NOT the right-hand side of operators in general.
+=
是赋值运算符,+
不是.
+=
is an assignment operator, +
is not.
赋值表达式的语法是:
assignment-expression: 条件表达式 逻辑或表达式分配运算符初始化程序子句 throw-expression assignment-operator:其中之一= *= *= /= %= += -= >>= <<= &= ^= |=
assignment-expression: conditional-expression logical-or-expression assignment-operator initializer-clause throw-expression assignment-operator: one of= *= *= /= %= += -= >>= <<= &= ^= |=
这篇关于为什么我可以在运算符+ =的右侧使用初始化程序列表,但不能在运算符+的右侧使用初始化程序列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!