![](/img/trans.png)
[英]error C2440: '=': cannot convert from 'std::list<std::string,std::allocator<_Ty>> *'to 'std::string*'
[英]error C2440: 'initializing': cannot convert from 'initializer list' to 'std::vector<char *,std::allocator<_Ty>>'
我試着編譯以下代碼:
vector<char*> art = { "a","an","the" };
但收到錯誤信息:
error C2440: 'initializing': cannot convert from 'initializer list' to 'std::vector<char *,std::allocator<_Ty>>'
1> with
1> [
1> _Ty=char *
1> ]
1> note: No constructor could take the source type, or constructor overload resolution was ambiguous
如果我將元素類型更改為'const char *',如下所示:
vector<const char*> art = { "a","an","the" };
它可以編譯。有人告訴我原因嗎?非常感謝。
這里有兩件事。 第一個也是最基本的一個,就是字符串文字在C ++中是默認的const
。 沙迪在答案中給出了很好的聯系。
第二件事是大括號初始化不能接受縮小轉換。 這在Meyers的Effective Modern C ++書籍的第 7項中得到了很好的解釋,非常可取。
這是類型系統的問題:當你用大括號內的值初始化容器時,比如{ "a","an","the" };
,這個支撐表達式被推導為具有類型std::initializer_lists<const char *>
,然后它將調用容器的構造函數,該構造函數將初始化列表作為參數。 但是,請記住,字符串文字在C ++中具有類型const char *
,但是您聲明了向量以保存char *
類型的元素。 這將意味着縮小轉換const char * -> char *
,其中大括號初始化不允許。 因此,此構造函數將被丟棄,找不到其他構造函數,並且您的編譯器會抱怨。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.