使用 C++,我尝试为我的类实现 toString() 函数:
void ClassName::toString(string& returnString)
{
sprintf(returnString.c_str(), "Position: (%f, %f, %f)\n", position.x, position.y, position.y);
}
但是我不断收到此错误:const char* 类型的参数与 char* 类型的参数不兼容
如何解决这个问题并使参数不再为常量?
最佳答案
How do I fix this?
使用不同的方法,使用stringstream
代替或使用辅助缓冲区。
void ClassName::toString(string& returnString)
{
std::stringstream ss;
ss << "Position: (" << position.x << ", " << position.y << ", "
<< position.z << ")\n");
returnString = ss.str();
}
and make the argument no longer const?
不要。如果将 c_str
更改为非常量类型,后果将不堪设想。程序员同胞们一定会流泪的。天使将失去翅膀。小猫会死。石油价格将会上涨。股市崩盘。僵尸启示录。
它是const
是有原因的 - 所以你不能修改它。这样做会导致未定义的行为。
关于C++ toString() 和 sprintf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11892774/