简体   繁体   中英

C++ Overloading '--' postfix operator

I'm trying to overload the '--' postfix operator. I have this code:

class Counter
{
 private:
    int count;
 public:
    Counter()
    { count = 0; }
    Counter(int c)
    { count = c; }

    void setCount(int c)
    { count = c; }
    int getCount()
    { return count; }

    int operator--()
    {
       int temp = count;
       count = count - 1;
       return temp;
    }
};

Then in main I have this function call:

 Counter a; 
 a.setCount(5); 
 cout << a-- << endl;

This gives me this error: error: no 'operator--(int)' declared for postfix '--', trying prefix operator instead

But when I call the operator-- function like this, it works just fine:

 cout << a.operator--() << endl;

What gives? It should be working fine.

For overloading postfix operator you need to specify a dummy int argument in the function signature ie there should also be a operator--(int) . What you have defined is a prefix decrement operator. See this FAQ for more details.

The postfix operator takes a int as an argument to distinguish it from the prefix operator.

Postfix:

int operator--(int)
{
}

Prefix:

int operator--()
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM