在 C++ 中为一个操作数重载二元运算符

Overloading a binary operator for one operand in c++

你能否在 C++ 中重载二元运算符以仅进行一次运算运行d?

我尝试使用类似于此的 class 来实现:

#include <iostream>

using namespace std;

class IntWrap {
public:
    IntWrap operator=(int rhs) {
        val = rhs;
        return *this;
    }

    // No second operand for +
    IntWrap operator+() {
        IntWrap result;
        result = val + 1;
        return result;
    }

    int Val() {return val;}

private:
    int val;
};

这段代码竟然是用GCC编译的,这让我很惊讶,它甚至没有用-Wall

给出任何警告

我 运行 遇到的问题实际上是使用重载运算符。

这不会编译,因为 GCC 期望在 +:

之后有一个 ope运行d
int main() {
    IntWrap test;
    test = 0;

    test +; // GCC expects an operand after +

    return 0;
}

成员函数可以与test.operator+()一起使用,但并没有真正使用运算符。

因此,更具体地说,C++ 标准是否允许仅使用一个 ope运行d 重载二元运算符?如果是这样,是否可以使用运算符符号调用重载函数,可能通过对右侧 ope运行d?

使用某种虚拟值

另外,别担心,我不打算在任何实际代码中使用它,我只是好奇,因为我找不到任何关于它的信息。

您没有重载二元运算符,而是 unary + 运算符。正确的用法是

IntWrap test;
test = 0;
+test;

N4140 [over.oper]/6:

It is not possible to change the precedence, grouping, or number of operands of operators.

在您的代码中,您重载了一元 + 运算符,而不是二元运算符。

Can you overload a binary operator to take only one operand in C++?

不,你不能那样做。运算符重载不允许您更改语言的语法或运算符优先级。它只允许您更改使用运算符时发生的情况。

你做了什么

IntWrap operator+() { ... }

重载一元 + 运算符。

您应该可以使用:

IntWrap test;
test = 0;
+test;