2013-06-28 20 views
0
#include <iostream> 
#include <string> 

int main(int argc, char *argv[]) 
{ 
    std::string s = {123}; 
    std::cout << s << std::endl; 
} 

爲什麼此程序打印{作爲輸出?它是底層詞法分析器中的一個錯誤,它只打印前面的{此輸出是有效的還是編譯器錯誤?

我用g ++ 4.8.1編譯過(沒有錯誤或警告)。 MSVC不編譯這種抱怨string不是一個聚合類型。

+3

123是ASCII碼{ – emartel

+0

類似:http://stackoverflow.com/questions/15736282/what-is-this-smiley-with-beard-expression – legends2k

回答

7

您在列表中初始化一個帶有字符數組的字符串。 123ASCII code of {。沒有編譯器錯誤。

要調用的構造是std::string的initalizer列表構造(參見here用於參考),如由段的C++ 11標準的21.4.2/15中規定:

basic_string(std::initializer_list<CharT> init, 
      const Allocator& alloc = Allocator()); 

效果:與basic_string(il.begin(), il.end(), a)相同。

MSVC不支持列表初始化,這就是爲什麼你收到消息抱怨string不是聚合的事實。

相關問題