简体   繁体   English

如何正确重载算术运算符,以便在C ++中“ 3” +“ 4”可以为“ 7”

[英]How to correctly overload arithmetic operator so that “3” + “4” can be “7” in c++

I overloaded + with 我超载+

string operator+(string a, string b);

it works when I do this: 当我这样做时它起作用:

string a = "3";
string b = "4";
cout << a + b;

However when I do this, it fails and with error message: invalid operand to binary expression(const char * and const char* ) 但是,当我这样做时,它将失败并显示错误消息:二进制表达式的无效操作数(const char *和const char *)

cout << "3" + "4";

Can someone tell me how to solve this problem? 有人可以告诉我如何解决这个问题吗?

Thanks for reply, I see why there is an error, I shouldn't overload operator in c++ which operand is built-in type. 感谢您的答复,我明白了为什么会出错,我不应该在c ++中重载运算符,该操作数是内置类型。

You can't overload an operator unless you make at least one of the arguments a user defined type, so what you ask is impossible. 除非您将至少一个自变量设置为用户定义的类型,否则您不能重载运算符,因此您无法提出要求。 However, the nearest you could come to that syntax is to perhaps use user defined literals. 但是,最接近该语法的地方可能是使用用户定义的文字。 In C++14, the s suffix is defined to create a std::string . 在C ++ 14中, s后缀被定义来创建std::string

using namespace std::string_literals;
std::cout << "3"s + "4"s;

If you can't use C++14, but can use C++11, then you can define your own literal suffix. 如果您不能使用C ++ 14,但是可以使用C ++ 11,则可以定义自己的文字后缀。

std::string operator""_s (const char* cs, size_t)
{
    return std::string(cs);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM