How to overload operator + for const char* and int

∥☆過路亽.° 提交于 2019-12-25 05:49:05

问题


I know this is silly and ugly, but I'm migrating some code automatically. My source language allows implicit conversion between strings and ints, and for example this is allowed:

var = "hello " + 2
print(var) # prints "hello 2"

How can I in C++ overload the + operator for const char* and int? I'm getting the error:

error: ‘std::string operator+(char* const&, int)’ must have an argument of class or enumerated type


回答1:


What you are asking for is illegal

To legally overload an operator at least one of the operands involved has to be a user-defined type. Since neither char* nor int is user-defined, what you are trying to accomplish isn't possible.

This, what you are trying to do, is intentionally, and explicitly, disallowed in the standard. Don't you think it would be weird if suddenly 1+3 = 42 because someone "clever" have defined an overload for operator+(int, int)?


What does the Standard say? (n3337)

13.3.1.2p1-2 Operators in expressions [over.match.oper]

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.

If either operand has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be neccessary to convert the operand to a type that is appropriate for a built-in operator.

( Note: The wording is the same in both C++03, and the next revision of the standard; C++14 )



来源:https://stackoverflow.com/questions/24088148/how-to-overload-operator-for-const-char-and-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!