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

Pas*_*zza 2 c++ pointers bit-shift bit

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

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);
}
Run Code Online (Sandbox Code Playgroud)

(上面的代码不编译)

预期产量: 35

Cle*_*rer 5

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"));   
}
Run Code Online (Sandbox Code Playgroud)

然而,这可能不是一个好主意.