我今天注意到在示例代码中:
void print(unsigned short a) {
std::cout << a << std::endl;
}
初始化和使用是这样的:
print(short (5));
但不是这样的:
print(unsigned short(6));
main.cpp:16:8: error: expected primary-expression before 'unsigned' print(unsigned short(6));
这与类型无关,因为这也有效:
typedef unsigned short ushort;
print(ushort (6));
所以我开始搜索标准中关于值初始化的内容。结果一无所获:
The effects of value initialization are:
1) if T is a class type ...
2) if T is a non-union class type ...
2) if T is a class type ...
3) if T is an array type, ..
4) otherwise, the object is zero-initialized.
为便于阅读而进行了修改。 Original source .
POD的值初始化规则是什么?类型? unsigned
限定类型无法进行值初始化的原因是什么?这是否与它们是 rvalues
的事实有关?
最佳答案
What is the reason that
unsigned
qualified types can't be value initialized?
只是因为 functional cast expression 中只能使用单字类型名称, 而 unsigned short
不是单字类型名称; 短
是。
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.
正如您所展示的,您可以使用 typedef
作为解决方法,或添加括号以将其更改为 c 风格的强制转换表达式,例如(unsigned short)(6)
,或 (unsigned short)6
.
根据标准,§7.6.1.3/1 Explicit type conversion (functional notation) [expr.type.conv] :
A simple-type-specifier or typename-specifier 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.
simple-type-specifier: nested-name-specifier opt type-name nested-name-specifier template simple-template-id nested-name-specifier opt 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 )
typename-specifier: typename nested-name-specifier identifier typename nested-name-specifier template opt simple-template-id
关于c++ - 直接初始化 unsigned short 的标准行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51893895/