2015-03-25 146 views
18

我最近一直震動本:爲什麼map <string,string>接受int值作爲值?

#include <map> 
#include <string> 
#include <iostream> 

using namespace std; 

int main() { 
    map<string, string> strings; 
    strings["key"] = 88; // surprisingly compiles 
    //map<string, string>::mapped_type s = 88; // doesn't compile as expected 

    cout << "Value under 'key': '" << strings["key"] << "'" << endl; 

    return 0; 
} 

它打印出 'X' 這是ASCII 88。

爲什麼字符串映射接受整數作爲值?地圖的文檔operator[]表示它返回mapped_type&這是string&在這種情況下,它沒有從int隱式轉換,是嗎?

+9

相關:[爲什麼C++允許將整數分配給字符串?](http://stackoverflow.com/q/1177704/335858)。 – dasblinkenlight 2015-03-25 12:10:02

回答

20

這是因爲,正如你所說,operator[]返回std::string&,它定義了operator= (char c)。您的註釋示例不會調用賦值運算符,它是copy-initialization,它將嘗試調用該類的顯式構造函數,其中在std::string中沒有適用的構造函數。

3

要完成圖片,請注意:

strings[88] = "key"; 

不能編譯,因爲從char/int沒有std::string構造。對於charstd::string只定義了賦值運算符。

相關問題