2016-11-23 51 views
35

爲什麼在C++中以下是非法的?爲什麼構造函數語法不能與「unsigned int」類型一起使用?

auto x = unsigned int(0); 

而下面的都是OK:

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

或一般:

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

(與Type例外是unsigned int)。

+3

當然,你可以只說 '汽車A = 10U',但你可能知道。您使用的語法與構造無關,即使它與表面相似。使用正確類型的文字,就是這樣。 –

回答

32

的語法是Explicit type conversion (functional notation)這裏。根據語法規則,它僅適用於簡單類型說明符或typedef說明符(即單字類型名稱)。

(重點煤礦)

2)的功能轉換表達式包括一個簡單的類型說明符或換句話說一個typedef說明符(的,只有一個字的類型名稱:unsigned int(expression)int*(expression)無效 ),然後是括號中的單個表達式。此演員表達式與相應的C風格演員表達式完全等效。

您可以將其更改爲C樣式轉換表達或static_cast,或用typedef符使用它作爲@讓FrançoisFabre建議。 $5.2.3/1 Explicit type conversion (functional notation) [expr.type.conv]

簡單型說明符([dcl.type.simple])或類型名稱說明符([temp.res]),接着以帶括號的可選從標準

auto x1 = (unsigned int)(0); 
auto x2 = static_cast<unsigned int>(0); 

行情, expression-list或由braced-init-list(初始化程序)構造給定初始化程序的指定類型的值。

而且$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) 
+0

我假設'unsigned(0)'也可以。 – Asu

+0

@Asu是的,因爲它是一個簡單的類型說明符。 – songyuanyao

+0

你能具體說明報價是從哪裏來的嗎?謝謝:) – Steve

20

由於解析優先。編譯器丟失,因爲int(0)匹配unsigned int之前。

你必須附上您在括號中鍵入:

auto x = (unsigned int)(0); 

或使用typedef:

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

我不確定「運算符優先級」在這裏是否合適。 – juanchopanza

+3

我也不確定。你會建議什麼?解析優先權?我正在編輯這種方式。 –

+3

解析優先級可能足夠清晰,但這實際上只是語言語法的規則。函數式轉換必須是單個標識符。 –

相關問題