gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:24:40 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com