0

I know there have been many questions posted about operator overload, but I can't get my code to work with any of the examples I find. Yes, I have taken a look at this link, but I am still having trouble understanding this.

I am trying to overload just the prefix operator, but I get an error saying that postfix expects an int. I am NOT trying to modify the postfix operator. I have a .h file, and a .cpp file. Inside of my .h file I have something like:

class X{
public:
        /* ... declarations of X ... */
        X& operator--(X& x);
};

And inside of my .cpp file I have something like:

#include "X.h"
namespace X{
X& X::operator--(X& x){/*...*/}
}

Can anyone tell me what I am doing incorrectly?

Community
  • 1
  • 1
K. Shores
  • 875
  • 1
  • 18
  • 46

2 Answers2

2

The prefix -- operator takes no arguments. Its definition should be as follows:

public:
    /* ... declarations of X ... */
    X& operator--();
};

And similarly when implementing it:

#include "X.h"
namespace X {
    X& X::operator--() {/*...*/}
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1
X& operator--(X& x);

Must be:

X& operator--();

Background: The compiler sees that you've given your -- operator an argument. The postfix version of -- takes an argument, so it thinks you mean that one. But the type of that argument must by convention be int. So it tells you exactly that: postfix 'X& X::operator--(X&)' must take 'int' as its argument.

The compiler could also tell you something like prefix 'X& X::operator--(X&)' must not take any argument if it wanted to. But, oh well. That's the way it is. Producing any diagnostic message is enough to conform to the C++ standard.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62