调用返回 int 并存储到字符串 C++ 中的函数

call function that returns int and store into string c++

本文关键字:C++ 函数 字符串 返回 int 存储 调用      更新时间:2023-10-16

我正在尝试创建一个调用函数并连接返回字符串值的字符串。如果其中一个函数返回 int,我会得到一个错误。我在重载运算符方面没有太多经验,但我认为我需要重载 + 运算符才能完成这项工作。这是对的吗?或者有更好的方法可以做到这一点吗?

string str=getString1()+getString2()+getInt();

您可以使用std::to_string .

string str = getString1() + getString2() + std::to_string(getInt());

按照 vincent 的建议使用 std::to_string,您还可以以一种简单的方式重载 + 运算符:

// string + int
std::string operator+(const std::string &str, const int &i){
    std::string result = str + std::to_string(i);
    return result;
}
// int + string
std::string operator+(const int &i, const std::string &str){
    std::string result = std::to_string(i) + str;
    return result;
}

然后,您的原始代码应该按检查方式工作。

string str = getString1() + getString2() + getInt();

例:

td::cout << string("This is a number: ") + 5 << endl;
std::cout << 5 + string(" is a number.") << endl;

输出:

This is a number: 5
5 is a number.