c++ - 如何为 const char* 和 int 重载运算符 +

标签 c++ c++11 vb6-migration

我知道这既愚蠢又丑陋,但我正在自动迁移一些代码。我的源语言允许字符串和整数之间的隐式转换,例如,这是允许的:

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/

相关文章:

c++ - 将共享指针作为参数传递

.net - 此代码适用于 VB,但在 VB.NET 中会出现异常,为什么?

c++ - MySQL 连接器/C++ 问题

c++ - 从原始指针创建 weak_ptr<>

c++ - C++ 单元测试工具的建议

c++ - 如何在 Union 中初始化一个非 POD 成员

c++ - C++0x 是否支持 __stdcall 或 extern "C"capture-nothing lambdas?

c++ - OpenGL:地形未绘制(高度图)

c# - 这段代码是在创建 setter/getter 吗?我正在尝试将其翻译成 C#

VB.net 将结构传递给非托管 dll