将 int& 转换为字符串

Convert int& to string

这对于普通的 C++ 用户来说似乎微不足道,但我目前正在重新学习 C++。我有一个接受 int& 的函数,我想将该值添加到打印语句的字符串中。所以,我有这样的东西:

std::string getTest(void* dataGroup, int& xWidth, int& yHeight)
{
     std::string results = "";

     results += "\nxWidth is: " + xWidth;

     return results;
}

当我调用它时 运行 失败了。将按引用传递的 int& 值转换为可以添加到字符串的形式的正确方法是什么?

std::to_string(xWidth).

& 几乎无关紧要。 to_string 按值取 int,所以你的函数如何取值并不重要:按值、左值引用、右值引用、const 或非 const.. . 一切都会起作用。