将字符串转换为 const* 字符

Converting string to const* char

本文关键字:字符 const 字符串 转换      更新时间:2023-10-16

我有两个string声明:

  1. killerName
  2. victimName

我需要将这两个字符串值转换为 const* 字符。

如何使用我的方法的示例:

if (killer.IsRealPlayer) {
   killerName = killer.GetName(); -- need to convert to const* char
   victimName = victim.GetName(); -- need to convert to const* char
   Notice(killerName + "has slain:" + victimName, killer.GetMapIndex(), false); 
}

我收到一些错误:

错误

111 错误 C2664:"通知":无法将参数 1 从"std::basic_string<_Elem,_Traits,_Ax>"转换为"常量字符 */

函数似乎Notice具有类型 const char * 的第一个参数 但是,作为第一个参数传递给它的表达式

killerName + "has slain:" + victimName

具有类型 std::string

只需按以下方式调用函数

Notice( ( killerName + "has slain:" + victimName ).c_str(), killer.GetMapIndex(), false); 
Notice(string(killerName + "has slain:" + victimName).c_str(), killer.GetMapIndex(), false); 

std::string::c_str()const char*提供给缓冲区。 我想这就是你想要的。

请参阅:http://www.cplusplus.com/reference/string/string/c_str/

正如其他人已经写过的,killerName + "has slain:" + victimName的结果是 std::string 型。因此,如果您的Notice()函数需要const char*作为第一个参数,则必须从 std::string 转换为 const char* ,并且由于没有为 std::string 定义隐式转换,因此必须调用 std::string::c_str() 方法:

Notice((killerName + "has slain:" + victimName).c_str(), killer.GetMapIndex(), false); 

但是,我想问一下:为什么您Notice()期望将const char*作为第一个参数?
只使用const std::string&会更好吗?通常,在现代C++代码中,您可能希望使用字符串类(如 std::string),而不是原始char*指针。

(另一种选择是有两个Notice()重载:一个期望const std::string&作为第一个参数,另一个期望const char*,如果由于某种原因const char*版本在您的特定上下文中确实有意义;例如在std::fstream构造函数中使用这种双重重载模式。