如何重载前面没有标识符的操作符

C++ How to overload an operator without an identifier before it

本文关键字:标识符 操作符 前面 何重载 重载      更新时间:2023-10-16

例如:

#include <iostream>
using namespace std;
int main(){
int a;
+a;
}

我希望算术加"+"操作符被重载,这样如果它出现在一个标识符之前(在本例中是"a"),它将打印"Hello",在"+"操作符之前没有另一个标识符,基本上不像这样:"identifierA+identifierB",而是像这样"+identifierB"(在本例中是"+a"),程序编译的结果是"Hello"。这怎么可能呢?

提前感谢您的帮助。

正如在注释中提到的,c++中不允许重载基本类型的现有操作符。您可以为用户定义的类型重载操作符,但这不是您的问题。