[英]error C2440: 'initializing': cannot convert from 'initializer list' to 'std::vector<char *,std::allocator<_Ty>>'
I tried to compile the following codes: 我试着编译以下代码:
vector<char*> art = { "a","an","the" };
but received error message: 但收到错误信息:
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
If i changed the element type to 'const char *' like this: 如果我将元素类型更改为'const char *',如下所示:
vector<const char*> art = { "a","an","the" };
it can be compiled.Can someone tell me the reason?Thanks a lot. 它可以编译。有人告诉我原因吗?非常感谢。
There are two things going on here. 这里有两件事。 First and the most basic one, is that string literals are const
by default in C++. 第一个也是最基本的一个,就是字符串文字在C ++中是默认的const
。 Shadi gave a very good link in his answer . 沙迪在答案中给出了很好的联系。
The second thing is that brace initialization cannot accept narrowing conversions. 第二件事是大括号初始化不能接受缩小转换。 This is very well explained in the item 7 of Meyers' Effective Modern C++ book, very advisable one. 这在Meyers的Effective Modern C ++书籍的第 7项中得到了很好的解释,非常可取。
It's a matter of the type system: when you initialize a container with values within braces, like in { "a","an","the" };
这是类型系统的问题:当你用大括号内的值初始化容器时,比如{ "a","an","the" };
, this braced expression is deduced to have the type std::initializer_lists<const char *>
, which then will call the container's constructor that takes an initializer list as a parameter. ,这个支撑表达式被推导为具有类型std::initializer_lists<const char *>
,然后它将调用容器的构造函数,该构造函数将初始化列表作为参数。 But, remember that string literals have type const char *
in C++, but you declared your vector to hold elements of type char *
. 但是,请记住,字符串文字在C ++中具有类型const char *
,但是您声明了向量以保存char *
类型的元素。 This will imply a narrowing conversion const char * -> char *
, which brace initialization doesn't allow. 这将意味着缩小转换const char * -> char *
,其中大括号初始化不允许。 Therefore, this constructor is discarded, no other is found, and your compiler complains. 因此,此构造函数将被丢弃,找不到其他构造函数,并且您的编译器会抱怨。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.