2012-06-27 90 views
0

我想重载' - '后缀操作符。我有这样的代码:C++重载' - '后缀操作符

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; 
    } 
}; 

然后在main我有这样的函数调用:

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

这给了我这个错误: error: no ‘operator--(int)’ declared for postfix ‘--’, trying prefix operator instead

但是,当我打电话operator--功能这样的,它工作得很好:

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

什么给?它应该工作正常。

+1

这是因为'a.operator - ()'等同于'--a'。 – chris

回答

8

要重载postfix操作符,您需要在函数签名中指定一个虚拟int参数,即应该也有一个operator--(int)。你定义的是一个前缀递减运算符。有关更多详细信息,请参阅此FAQ

+2

如果你(OP)想知道为什么,这是因为他们只是需要一些方法来区分后缀和前缀。 (也许这很明显) –

+0

谢谢,我忘了这一点,谢谢你的回答。 @BenjaminLindley Gotcha,所以这是一个遵循的规则,很有道理谢谢! – rcorrie

+0

@BenjaminLindley它是定义后缀和前缀版本的标准吗?我的意思是为什么我无法用带前缀版本的int参数定义运算符++? –

8

后缀运算符将int作为参数将其与前缀运算符区分开来。

后缀:

int operator--(int) 
{ 
} 

前缀:

int operator--() 
{ 
}