我想将char传递给需要字符串的参数。
void test(const string&);
test('a'); // does not like
error: invalid user-defined conversion from ‘char’ to ‘const string& {aka const std::basic_string<char>&}’
我知道我可以将'更改为',但是在我的实际代码中,这还不是文字。
我如何方便地进行编译?
没有从字符到字符串的隐式转换。您必须使用适当的构造函数创建一个字符串,该构造函数具有另一个参数来指定长度:
test(std::string(1, 'a'));
或者,从C ++ 11开始,带有初始化列表
test({'a'}); // if there are no ambiguous overloads of "test"
test(std::string{'a'}); // if you need to specify the type
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句