c++ - 如何将 char 传递给需要字符串的函数

标签 c++

我想将一个字符传递给需要字符串的参数。

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

关于c++ - 如何将 char 传递给需要字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24530144/

相关文章:

c++ - 使用 ArrayFire 库

c++ - 在 C++ 中返回 "This"对象的函数

c++ - 使用 BFS 寻找图中的最短路径

c++ - delete p 在析构函数中执行

c++ - QTableWidget、Cellwidget、QLabel

C++ 使用构造函数参数初始化成员数组

c++ - 这是否被视为复制构造函数?

c++ - C++中的 namespace 搜索

c++ - 使用 boots::spirit::qi 进行解析的 TBB 并行化

c++ - 在 C++ 中,哪种数据类型用于非常大的数字?