错误C2440:&#39;初始化&#39;:无法转换为&#39;初始化列表&#39; to&#39; std :: vector <char *,std :: allocator <_ty =“”>&gt;&#39;

时间:2018-04-04 06:09:33

标签: c++

我尝试编译以下代码:

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

如果我将元素类型更改为&#39; const char *&#39;像这样:

vector<const char*> art = { "a","an","the" };

它可以编译。有人告诉我原因吗?非常感谢。

2 个答案:

答案 0 :(得分:2)

这里有两件事。第一个也是最基本的一个,就是C ++中默认的字符串文字是const。 Shadi在his answer中提供了一个非常好的链接。

第二件事是大括号初始化不能接受缩小转换。这在Meyers&#39;的第7项中得到了很好的解释。 Effective Modern C++本书,非常明智。

它是类型系统的问题:当您使用大括号内的值初始化容器时,例如在{ "a","an","the" };中,此支撑表达式被推断为具有类型std::initializer_lists<const char *>,然后将调用容器的构造函数,该构造函数将初始化列表作为参数。但是,请记住,字符串文字在C ++中具有类型const char *,但是您声明了向量以保存char *类型的元素。这将意味着缩小转换const char * -> char *,这使得初始化不允许。因此,此构造函数将被丢弃,找不到其他构造函数,并且您的编译器会抱怨。

答案 1 :(得分:1)

原因是字符串文字是常量,它们存储在只读内存中。 Why

如果它适合您,您也可以使用:

vector<string> art = { "a","an","the" };