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

C++ 重载C+中字符串的左移位运算符+;,c++,pointers,bit,bit-shift,C++,Pointers,Bit,Bit Shift,我如何使字符串的左移位运算符过载,有人能帮我吗 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 <

我如何使字符串的左移位运算符过载,有人能帮我吗

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);
}
常量字符*
{

int operatorC++不允许只对内置类型重载运算符。因此,不可能为指向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"));   
}
#包括
#包括
#包括
自动运算符int
{
返回std::atoi(a.c_str())+std::atoi(b.c_str());
}
int main()
{

std::cout C不支持运算符重载。不要垃圾邮件标记您永远无法让代码执行您想要的操作-运算符重载必须至少包含一个用户定义的类型。这是否可以编译?顺便说一句-
atoi
是垃圾。是否检查errors@EdHeal不,这不会编译。OP正在询问如何重新编写它o它确实编译::)Akal-它是一个移位运算符,至少是C++规范所关注的。更好地使用(const string和a,const string & b)您可以在C++17中使用
std::string\u view
,并避免与
std::string
相关的大量开销。甚至可以通过使用用户定义的字符串视图文字使其更具可读性。@StoryTeller我只能同意。我不会改进答案,因为我不建议在前面做类似的事情t place.我可以理解:)
atoi
只有在您已经知道字符串可以解析为整数,或者0表示错误的情况下才能安全使用。请改用
std::stoi