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

2020-04-10 02:58发布

问题:

I'm not able to compile the below code, but i'm able to compile it under visual studio with another laptop, I don't no if there are a different configuration that shout be set.

#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();
}

and it's giving the below error :

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

回答1:

Operator ++ actually has two meanings, depending on whether it is used as prefix or as postfix operator. The convention of which function C++ expects to be defined in your class when used in the one way or in the other is as follows:

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

Your function void operator++() does not fulfil this convention, that's why the error appears.

The implementation could look as follows:

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