c++ - 如何重载就地和复制字符串操作函数?

标签 c++ overloading ambiguous-call

我希望能够做到以下几点:

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/

相关文章:

C++ 继承错误 : ambiguous error

haskell - 使用 DuplicateRecordFields 消除记录更新的歧义

c++ - 在 if 语句评估中 boost scoped_lock 对象

C++ - 如何获取结构的最后一个成员类型以及从现有对象访问它的方法?

c++ - 以 24 小时格式比较 C/C++ 中的小时数

c++:没有重载函数的实例

C++ 没有运算符 ">>"匹配这些操作数(<string> 包含在 header 中)

c++ - 为什么我们在使用宏时找不到合适的运算符重载?

c++ - 函数重载与函数变量初始化

c++ - 跨基类解决虚方法重载