Search code examples
c++operator-overloadingdecrementunary-operator

Operator overloading confusion


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?


Solution

  • 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--() {/*...*/}
    }