如何为const char *和int重载operator + [英] How to overload operator + for const char* and int
问题描述
我知道这很愚蠢,但是我正在自动迁移一些代码。我的源语言允许在字符串和整数之间进行隐式转换,例如,允许这样做:
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"
如何在C ++中重载+ const char *
和 int
的运算符?我收到错误消息:
How can I in C++ overload the + operator for const char*
and int
? I'm getting the error:
错误: std :: string运算符+(char * const& int)必须具有
类或枚举类型的参数
error: ‘std::string operator+(char* const&, int)’ must have an argument of class or enumerated type
推荐答案
您要的是非法的
要合法地重载运算符,至少涉及的一个操作数必须是用户定义的类型。由于 char *
和 int
都不是用户定义的,因此您要尝试完成的任务
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.
这是您要尝试执行的操作,在标准中有意且明确地不允许这样做。您是否认为如果突然 1 + 3 = 42
会很奇怪,因为有人聪明已经为 operator +(int,int)
定义了重载?
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)
?
13.3.1.2p1-2
表达式中的运算符[ over.match.oper]
如果表达式中没有运算符的操作数具有类或枚举类型,则假定该运算符是内置运算符,并根据第5章进行了解释。
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.
(注意: C ++ 03 和标准的下一修订版中的措词相同; C ++ 14 )
( Note: The wording is the same in both C++03, and the next revision of the standard; C++14 )
这篇关于如何为const char *和int重载operator +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!