本文介绍了没有从'value_type'(aka'char')到'string'(aka'basic_string< char,char_traits< char> ;,分配器< char>')的可行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
string convert(string name)
{
string code = name[0];
...
}
我从这行得到从'value_type'(aka'char')到'string'(aka'basic_string,allocator>')的不可行转换".
I get "no viable conversion from 'value_type' (aka 'char') to 'string' (aka 'basic_string, allocator >')" from this line.
如果我将其更改为:
string convert(string name)
{
string code;
code = name[0];
...
}
然后它起作用.谁能解释为什么?
Then it works.Can anyone explain why?
推荐答案
类std :: string(相应地std :: basic_string)具有赋值运算符
Class std::string (correspondingly std::basic_string) has assignment operator
basic_string& operator=(charT c);
,此代码段中使用了该赋值运算符
and this assignment operator is used in this code snippet
string convert(string name)
{
string code;
code = name[0]; // using of the assignment operator
...
}
但是该类没有合适的构造函数,您可以编写
However the class does not has an appropriate constructor that you could write
string code = name[0];
您可以这样写
string code = { 1, name[0] };
或喜欢
string code( 1, name[0] );
使用构造函数
basic_string(size_type n, charT c, const Allocator& a = Allocator());
这篇关于没有从'value_type'(aka'char')到'string'(aka'basic_string< char,char_traits< char> ;,分配器< char>')的可行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!