c++ - no viable conversion from 'value_type' (aka 'char') to 'string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') -


string convert(string name) {   string code = name[0];   ... } 

i "no viable conversion 'value_type' (aka 'char') 'string' (aka 'basic_string, allocator >')" line.

if change to:

string convert(string name) {   string code;   code = name[0];   ... } 

then works. can explain why?

class std::string (correspondingly std::basic_string) has assignment operator

basic_string& operator=(chart c); 

and assignment operator used in code snippet

string convert(string name) {   string code;   code = name[0]; // using of assignment operator   ... } 

however class not has appropriate constructor write

string code = name[0]; 

you can write either like

string code = { 1, name[0] }; 

or like

string code( 1, name[0] ); 

using constructor

basic_string(size_type n, chart c, const allocator& = allocator()); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -