2014-11-08 162 views
1

我有这个代码的问题:从'char'到'const char *'的C++无效转换[-fpermissive] |

void keylist(char key) 
{ 
    //check if the user presses a key 
    if(GetAsyncKeyState(key)) 
    { 
     string skey = key; 
     buffer.append(skey); 
     counter++; 

    } 
} 

每次我尝试运行它给我这个错误的程序: 代码块项目\ CB32KLG \ main.cpp中| 66 |错误:从“字符”无效的转换到'const char *'[-fpermissive] |

回答

6

这是因为这

string skey = key; 

有没有在字符串中没有重载构造函数只需要字符作为其input.See下面的完整列表: -

string(); 
string (const string& str); 
string (const string& str, size_t pos, size_t len = npos); 
string (const char* s); 
string (const char* s, size_t n); 
string (size_t n, char c); 
template <class InputIterator> 
    string (InputIterator first, InputIterator last); 

要解决,你可以使用: -

string skey(1, key); 
+1

又该做些什么来解决我的代码? xD – 2014-11-08 10:48:26

+0

请看我更新的答案 – ravi 2014-11-08 10:49:56

3
string skey = key; 

string中只有char没有可行的转换构造函数。
初始化这样的:

string skey{key}; 

或者这样:

string skey(1, key); 
+0

Anoter(有点令人惊讶)选项是使用'string skey; skey = key;'。初始化是不允许的,但赋值是(并且是字符整数,它也意味着这是完全合法的'std :: string s; s = 3.14;') – 6502 2014-11-08 10:54:22

相关问题