如何将char传递给期望字符串的函数

时间:2014-07-02 11:38:08

标签: c++

我想将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>&}’

我知道我可以改变&#39;到了&#34;,但在我的真实代码中,它不是那时的文字。

如何方便地编译?

4 个答案:

答案 0 :(得分:10)

没有从字符到字符串的隐式转换。你必须使用适当的构造函数创建一个字符串,它有另一个参数来指定长度:

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

答案 1 :(得分:4)

你可以像下面的例子一样使用卷曲的笔记本:

#include <string>
#include <iostream>

void test(const std::string&) { std::cout << "test!" << std::endl; }

int main() {
  test({'a'});
}

LIVE DEMO

答案 2 :(得分:2)

这听起来像是一个消息重载的工作。

void test(const string&);
void test(char);

并在您的课程实施中。

void yourclass::test(const string& aString)
{
...
}


void yourclass::test(char aChar)
{
  ::test(std::string(1,aChar));
}

答案 3 :(得分:1)

呃,可能会添加你自己的重载?

void test(char v)
{ test(string(1, v)); }

编辑: 我没有提到列出的C ++ 11答案,我认为你无法修改这些名词。如果是后者,并且你没有c ++ 11,那么为此创建一个宏/函数..

void to_string(char v)
{ return string(1, v); }

// Use
test(to_string('c'));

然后您可以处理所有案例(const char*char*等重载to_string()

相关问题