在面試寶典上看到一例子,要求找編譯時的錯誤

原題是這樣:有如下代碼,則編譯時會產生錯誤的是語句幾?

struct Test
{
     Test(int) {}
     Test() {}
     void fun() {}
};

int main()
{
    Test a(1);    // 語句1
    a.fun();        // 語句2
    Test b();      // 語句3
    b.fun();        // 語句4
    return 0;
}

 先報答案,這是我用 clang++ 編譯後的輸出信息:



第二條警告信息是:empty parentheses interpreted as a function declaration

意思是編譯器將 Test b(); 理解成了一個返回值爲 Test,參數爲 void 的函數聲明式。

而第三條警告信息又提示我們去掉 b 後面的括號,這樣編譯器就會將它識別爲了個變量定義。


針對這種情況標準中有特別說明:

ISO C++11 8.5
10 An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.
[ Note: Since () is not permitted by the syntax for initializer,
X a();
is not the declaration of an object of class X, but the declaration of a function taking no argument and
returning an X. The form () is permitted in certain other initialization contexts (5.3.4, 5.2.3, 12.6.2). —end note ]


相關參考:

http://en.wikipedia.org/wiki/Most_vexing_parse

http://blog.csdn.net/zldeng_scir/article/details/7098714

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章