为什么不能将构造函数语法与"unsigned int"一起使用?类型? [英] Why can constructor syntax not be used with the "unsigned int" type?
问题描述
为什么以下内容在C ++中是非法的?
Why is the following illegal in 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
除外).
推荐答案
语法为此处的显式类型转换(功能符号).根据语法规则,它仅适用于简单的类型说明符或typedef说明符(即单字类型名称).
The syntax is Explicit type conversion (functional notation) here. According to the grammatical rule, it only works with simple type specifier or typedef specifier (i.e. a single-word type name).
(重点是我的)
2)函数强制转换表达式由简单类型说明符或typedef说明符组成(换句话说,单个单词类型名称:
unsigned int(expression)
或int*(expression)
无效),后面加上括号中的单个表达式.该强制转换表达式与相应的C样式强制转换表达式完全等效.
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建议的那样.
You can change it to c-style cast expression or static_cast
, or use it with typedef specifier as @Jean-FrançoisFabre suggested.
auto x1 = (unsigned int)(0);
auto x2 = static_cast<unsigned int>(0);
来自标准报价, $ 5.2.3/1显式类型转换(功能符号)[expr.type.conv]
简单类型说明符([dcl.type.simple])或类型名称说明符([temp.res]),后跟带括号的可选表达式列表或括号初始化列表(初始化程序)构造给定初始值设定项的指定类型的值.
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简单类型说明符[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 )
这篇关于为什么不能将构造函数语法与"unsigned int"一起使用?类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!