起初我有这个:
LISP err(const char *message, LISP x)
{
return err(message, x, NULL);
}
LISP err(const char *message, const char *x)
{
return err(message, NULL, x);
}
然后我想给它连接另一个字符串,我就这样尝试了:
LISP err(const char* message, const char* x)
{
std::string full_message = "fromchar_" + std::string(message);
return err(full_message.c_str(), NULL, x);
}
LISP err(const char* message, LISP x)
{
const char* func_name = "fromlisp_";
const char* final_message = (message) ? (func_name + std::string(message)) : "?";
return err(final_message.c_str(), x, NULL);
}
这不编译,说 finalmessage 不属于 const char* 类。
我该如何解决这个问题?
chat.openai 甚至无法回答这个问题
这是完整的错误。
谢谢。
像这样
std::string final_message = (message) ?
(func_name + std::string(message)) :
std::string("?");
final_message
是 std::string
类型,您还必须使 ?:
的两个部分返回相同的类型。
但我会重写所有代码以始终如一地使用
std::string
。很明显,您更喜欢 char*
并且仅在需要集中两个字符串时才使用 std::string
。导致代码混乱,全程使用std::string
即可,比char*
灵活多了。