下面的代码会出现错误prog.cpp:5:13: error:无效的从' char '到' const char* '的转换

int main()
{
  char d = 'd';
  std::string y("Hello worl");
  y.append(d); // Line 5 - this fails
  std::cout << y;
  return 0;
}

我也尝试了,下面,它编译,但在运行时随机行为:

int main()
{
  char d[1] = { 'd' };
  std::string y("Hello worl");
  y.append(d);
  std::cout << y;
  return 0;
}

对不起,这个愚蠢的问题,但我已经搜索了谷歌,我能看到的只是“字符数组到字符ptr”,“字符ptr到字符数组”,等等。


当前回答

如果使用push_back,则不会调用string构造函数。否则,它将通过强制转换创建一个字符串对象,然后将该字符串中的字符添加到另一个字符串中。对一个小角色来说太麻烦了;)

其他回答

如果使用push_back,则不会调用string构造函数。否则,它将通过强制转换创建一个字符串对象,然后将该字符串中的字符添加到另一个字符串中。对一个小角色来说太麻烦了;)

使用push_back方法():

std::string y("Hello worl");
y.push_back('d')
std::cout << y;

问题在于:

std::string y("Hello worl");
y.push_back('d')
std::cout << y;

你必须使用d而不是使用char的名字,比如char d = 'd';还是我错了?

有三种方法: 例如,我们有这样的代码: Std::string str_value = "origin"; Char c_append = 'c'; 我们通常使用push_back()。 str_value.push_back (c) 使用+=。 Str_value += c 使用追加方法。 str_value.append (1 c) 你可以从http://www.cplusplus.com/reference/string/string/了解更多关于string的方法

y += d;

我将使用+=运算符而不是命名函数。