Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 568
Amjad Alkhatib Avatar asked Apr 07 '18 20:04

Amjad Alkhatib


1 Answers

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;
}
like image 65
Stephan Lechner Avatar answered Sep 18 '22 01:09

Stephan Lechner