为什么以下在 C++ 中是非法的?
auto x = unsigned int(0);
而以下都可以:
auto y = int(0);
auto z = unsigned(0);
auto w = float(0);
或一般来说:
auto t = Type(... c-tor-args ...);
(除了 Type
是 unsigned int
)。
最佳答案
语法是Explicit type conversion (functional notation)这里。根据语法规则,它只适用于简单类型说明符或 typedef 说明符(即单字类型名称)。
(强调我的)
2) The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name:
unsigned int(expression)
orint*(expression)
are not valid), followed by a single expression in parentheses. This cast expression is exactly equivalent to the corresponding C-style cast expression.
您可以将其更改为 c 风格的强制转换表达式或 static_cast
,或者按照@Jean-FrançoisFabre 的建议将其与 typedef 说明符一起使用。
auto x1 = (unsigned int)(0);
auto x2 = static_cast<unsigned int>(0);
引用标准,$5.2.3/1 Explicit type conversion (functional notation) [expr.type.conv]
A simple-type-specifier ([dcl.type.simple]) or typename-specifier ([temp.res]) followed by a parenthesized optional expression-list or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer.
还有 $7.1.7.2/1 Simple type specifiers [dcl.type.simple]
The simple type specifiers are
simple-type-specifier: nested-name-specifieropt type-name nested-name-specifier template simple-template-id nested-name-specifieropt template-name char char16_t char32_t wchar_t bool short int long signed unsigned float double void auto decltype-specifier type-name: class-name enum-name typedef-name simple-template-id decltype-specifier: decltype ( expression ) decltype ( auto )
关于c++ - 为什么构造函数语法不能与 "unsigned int"类型一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765232/