英文:
Why are curly braces {} NOT considered an operator in C++?
问题
我已查看官方操作符列表,但在任何操作符列表(无论是可重新定义还是不可重新定义的)中都没有看到{}
出现。
据我所知,{}
用于指定代码块,并且用于创建大括号初始化列表,但为什么在C++中不被视为操作符呢?
英文:
I've checked official operator list, but didn't see {}
appear in any list of operator (either redefinable or non-redefinable).
As far as I know, {}
is used to specify a block of code, and also used to create a braced-init-list, but why is NOT considered an operator in C++?
答案1
得分: 1
使用 {}
和诸如 +
、!
、()
等操作符的用法都属于表达式。具体来说,语言的语法包含以下规则(还有许多与表达式相关的规则):
这里的第一条规则匹配使用 ()
(调用操作符)的函数调用,例如 foo(0)
。第二条规则匹配使用给定类型的列表初始化,例如 int{0}
。
{}
和 ()
在语法上非常相似,事实上,将花括号初始化列表视为一个操作符也并不远离事实。然而,有两个特征可以区分操作符:
- 操作符通常是可组合的,这意味着你可以构建表达式,比如
x() + y()
、(&x)()
和x[0]()
。相比之下,花括号初始化列表只能应用于类型名称,用于初始化。{}
不能应用于另一个表达式。 - 操作符通常是可以重载的(有一些例外)。列表初始化要么执行某种内置初始化,要么调用构造函数。它不能使用
operator{}
进行重载,这与操作符的预期行为不同。
英文:
Uses of {}
, and uses of operators like +
, !
, ()
, etc. are expressions. Specifically, the language grammar contains the rule (among many others related to expressions):
> postfix-expression:<br>
> postfix-expression (
expression-list<sub>opt</sub> )
<br>
> simple-type-specifier braced-init-list<br>
> [...]
The first rule matches function calls with ()
(call operator) such as foo(0)
. The second rule matches list initialization with a given type, such as int{0}
.
{}
and ()
are quite similar gramatically, and it's not far from the truth to think of braced-init-list as an operator too. However, there are two features that distinguish operators:
- Operators are usually composable, meaning that you can form expressions like
x() + y()
,(&x)()
, andx[0]()
. By comparison, braced-init-lists can only be applied to the name of the type, to do initialization.{}
cannot be applied to another expression. - Operators are (with some exceptions) overloadable. List initialization is either performing some built-in initialization, or it calls a constructor. It is not overloadable using
operator{}
, as one would expect from an operator.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论