在 C++ 中重载字符串的左移运算符

Overloading the left shift operator for strings in C++

如何重载字符串的左移运算符,有人可以帮助我吗? :

const char*
{
    int operator<<(const char* rhs)
    {
        return std::atoi(this) + std::atoi(rhs);
    }
}

int main() {
    const char* term1 = "12";
    const char* term2 = "23";
    std::cout << (term1 << term2);
}

(以上代码无法编译)

预期输出:35

C++ 不允许纯粹为内置类型重载运算符。所以不可能重载指向 const char 的指针的左移。

juanchpanza 的回答是对的。您正在尝试做的事情无法完成,因为您使用的是内置类型。

但是,您可以使用自定义类型来实现,包括 std::string

下面的程序说明了如何做:

#include <iostream>
#include <cstdlib>
#include <string>

auto operator << (std::string a, std::string b) -> int
{
    return std::atoi(a.c_str()) + std::atoi(b.c_str());
}

int main()
{
    std::cout << (std::string("1") << std::string("2"));   
}

不过,这可能不是一个好主意。