我希望能够做到以下几点:
std::cout << str_manip("string to manipulate");
还有
std::string str;
str_manip(str);
std::cout << str;
为此,我有两个函数
#include <string>
// copying
std::string str_manip(std::string str)
{
// manipulate str
return str;
}
// in-place
void str_manip(std::string& str)
{
// manipulate str
}
但它们会产生以下错误:
error: call of overloaded 'str_manip(std::__cxx11::string&)' is ambiguous
我怎样才能克服这个问题?
最佳答案
问题出在这个调用上:
std::string str;
str_manip(str);
std::cout << str;
编译器不知道 str_manip
是哪个版本打电话。
您可以将函数更改为如下所示:
#include <string>
// copying
std::string str_manip(const std::string& str)
{
std::string dup = str;
// manipulate dup
return dup;
}
// in-place
void str_manip(std::string& str)
{
// manipulate str
}
现在,编译器知道模棱两可的调用必须是采用非 const
的函数。范围。您还可以确保返回 std::string
的调用到 <<
运算符(operator)没有修改您的字符串。
关于c++ - 如何重载就地和复制字符串操作函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287805/