Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::vector::operator[]不';t检验型_C++_Vector_Type Conversion - Fatal编程技术网

C++ std::vector::operator[]不';t检验型

C++ std::vector::operator[]不';t检验型,c++,vector,type-conversion,C++,Vector,Type Conversion,我有一个这样的结构: struct VrtxPros{ long idx; std::vector<std::string> pros; VrtxPros(const long& _idx=-1, const std::string& val="") : idx(_idx) { if ( !val.empty() && val!="" ) pros.push_back(val)

我有一个这样的结构:

struct VrtxPros{
    long idx;
    std::vector<std::string> pros;
    VrtxPros(const long& _idx=-1, const std::string& val="") : idx(_idx)
    {
         if ( !val.empty() && val!="" )
             pros.push_back(val);
    }
};
编译器对此没有问题。我想知道,因为接线员应该提供一份推荐信。 在
std::string
中有一个
操作符=
,它将接受一个长的as源


为什么代码要编译

可以将
std::string
分配给
char
,将
long
隐式转换为
char
,因此可以将
std::string
分配给
long
。您的编译器可能会对这种隐式转换发出警告(如果您还没有打开警告级别,您将看到它)

请参阅列出的#4
运算符=
。注意no只需要一个字符,所以这种事情只能在赋值时进行

为此,您也可以这样做:

std::string wow;
wow = 7ull; // implicit unsigned long long to char conversion
wow = 1.3f; // implicit float to char conversion

使用-Wconversion for g++获取从long到char的隐式转换警告。

basic\u string&operator=(图表ch);4) 将内容替换为字符ch
。您的
long
可能正在转换为字符。其他需要注意的是您的
!=“
检查是多余的,如果我没有遗漏什么,那么传递
”-1“
就可以了,因为
std::string
有一个
const char*
@mistapink的隐式转换构造函数,long可以隐式转换为
char
@mistapink,对于
CharT
,它是
std::basic_string
的第一个模板参数,它是
char
std::string
。相比之下,
CharT
对于
std::wstring
,应该是
wchar\t
。g++隐式地将int转换为char。@Hrishi,g++不应该是唯一的一个:
int x=999。。。;字符c1=x;//好的,虽然它可能会缩小(在本例中,它确实缩小)
取自C++11标准§8.5.4,但我从链接的示例中没有得到任何警告。只有
operator=
能做到这一点,而不是构造函数,所以大多数时候都是经过深思熟虑的。@chris在VS2010中,警告级别为4,我从你的代码和我的代码中得到了警告。@chris:是的,这是标准中规定的,不,我真的不明白为什么,但是在
std::basic_string
中有一个重载
operator=
,它接受一个
CharT
对象。你为什么要做这样的手术是我过去一直想知道的。啊,奇怪的是,我从来没有做过这样的手术。
std::string wow;
wow = 7ull; // implicit unsigned long long to char conversion
wow = 1.3f; // implicit float to char conversion