【问题标题】:Why can constructor syntax not be used with the "unsigned int" type?为什么构造函数语法不能与“unsigned int”类型一起使用?
【发布时间】:2017-04-07 12:11:31
【问题描述】:

为什么以下在 C++ 中是非法的?

auto x = unsigned int(0);

而以下都可以:

auto y = int(0);
auto z = unsigned(0);
auto w = float(0);

或一般来说:

auto t = Type(... c-tor-args ...);

Typeunsigned int 除外)。

【问题讨论】:

  • 当然你可以说'auto a = 10u',但你可能知道。您使用的语法与构造无关,即使它表面上类似于它。使用正确类型的文字,就是这样。

标签: c++ type-conversion language-lawyer


【解决方案1】:

因为解析优先级。编译器丢失,因为int(0)unsigned int 之前匹配。

您必须将您的类型括在括号中:

auto x = (unsigned int)(0);

或使用 typedef:

typedef unsigned int uint;
auto x = uint(0);

【讨论】:

  • 我不确定“运算符优先级”在这里是否正确。
  • 我也不确定。你有什么建议?解析优先级?我就是这样编辑的。
  • 解析优先级可能已经足够清楚了,但这实际上只是语言语法的规则。函数式强制转换必须是单个标识符。
【解决方案2】:

这里的语法是Explicit type conversion (functional notation)。根据语法规则,它只适用于简单类型说明符或 typedef 说明符(即单字类型名称)。

(强调我的)

2) 函数转换表达式由简单类型说明符或 typedef 说明符组成(换句话说,单个单词类型名称:unsigned int(expression)int*(expression) 无效),后跟括号中的单个表达式。这个强制转换表达式与对应的 C 风格强制转换表达式完全等价。

您可以将其更改为 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]

简单类型说明符 ([dcl.type.simple]) 或类型名称说明符 ([temp.res]) 后跟带括号的可选表达式列表或花括号初始化列表(初始值设定项)构造给定初始化器的指定类型的值。

还有$7.1.7.2/1 Simple type specifiers [dcl.type.simple]

简单的类型说明符是

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 )

【讨论】:

  • @Asu 是的,因为它是一个简单的类型说明符。
  • 您能否具体说明该报价的来源?谢谢:)
  • 引用和答案在说不同的东西;注意引号中的冒号:。引用说说明符必须是单字类型名称,但答案说single-word type specifier is not valid
猜你喜欢
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多