【问题标题】:C++ Overloading '--' postfix operatorC++重载'--'后缀运算符
【发布时间】:2012-06-27 03:48:56
【问题描述】:

我正在尝试重载“--”后缀运算符。我有这个代码:

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;

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

【问题讨论】:

  • 那是因为a.operator--() 等价于--a

标签: c++ class operator-overloading postfix-operator


【解决方案1】:

对于重载后缀运算符,您需要在函数签名中指定一个虚拟的int 参数,即还应该有一个operator--(int)。您定义的是前缀减量运算符。有关详细信息,请参阅此FAQ

【讨论】:

  • 如果你(OP)想知道为什么,那是因为他们只是需要一些方法来区分后缀和前缀。 (也许这很明显)
  • 谢谢,我忘记了,谢谢你的回答。 @BenjaminLindley Gotcha,所以这只是一个遵循的规则,有道理,谢谢!
  • @BenjaminLindley 它是定义后缀和前缀版本的标准吗?我的意思是为什么我不能用带前缀版本的 int 参数定义 operator++?
【解决方案2】:

后缀运算符将int 作为参数以区别于前缀运算符。

后缀:

int operator--(int)
{
}

前缀:

int operator--()
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 2012-01-05
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    相关资源
    最近更新 更多