c2676 - 二进制“++”未定义此运算符

c2676 - binary '++' does not define this operator

我无法编译下面的代码,但我可以在 visual studio 下用另一台笔记本电脑编译它,如果有不同的配置需要设置,我不会拒绝。

#include<iostream>
using namespace std;
class Unary {
private:
    int x, y;

public:
    Unary(int i = 0, int j = 0) {
        x = i;
        y = j;
    }
    void show()
    {
        cout << x << " " << y << endl;
    }
    void operator++()
    {
        x++;
        y++;
    }
};

int main() {
    Unary v(10, 20);
    v++;
    v.show();
}

它给出了以下错误:

Error C2676: binary '++': 'Unary' does not define this operator or a conversion to a type acceptable to the predefined operator

运算符++其实有两层意思,看它是用作前缀运算符还是用作后缀运算符。当以一种方式或另一种方式使用时,C++ 希望在 class 中定义哪个函数的约定如下:

class Unary {
  public:
    Unary& operator++ ();    // prefix ++: no parameter, returns a reference
    Unary operator++ (int);  // postfix ++: dummy parameter, returns a value
};

你的函数void operator++()不满足这个约定,所以才会出现这个错误。

实现可能如下所示:

Unary Unary::operator++(int)
{
    x++;
    y++;
    return *this;
}