我知道这既愚蠢又丑陋,但我正在自动迁移一些代码。我的源语言允许字符串和整数之间的隐式转换,例如,这是允许的:
var = "hello " + 2
print(var) # prints "hello 2"
我如何在 C++ 中为 const char*
和 int
重载 + 运算符?我收到错误:
error: ‘std::string operator+(char* const&, int)’ must have an argument of class or enumerated type
最佳答案
你所要求的是非法的
要合法地重载运算符,至少其中一个操作数必须是用户定义的类型。由于 char*
和 int
都不是用户定义的,因此您想要完成的目标是不可能的。
标准中有意且明确地禁止您尝试执行此操作。你不觉得如果突然 1+3 = 42
会很奇怪吗,因为有人“聪明”为 operator+(int, int)
定义了一个重载?
标准怎么说? ( 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.
( 注意:C++03 和标准的下一修订版中的措辞相同;C++14 )
关于c++ - 如何为 const char* 和 int 重载运算符 +,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24088148/