簡體   English   中英

C ++重載'-'后綴運算符

[英]C++ Overloading '--' postfix operator

我正在嘗試重載'-'后綴運算符。 我有以下代碼:

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;

是什么賦予了? 它應該工作正常。

對於重載postfix運算符,您需要在函數簽名中指定一個啞int參數,即也應該有一個operator--(int) 您定義的是前綴減量運算符。 有關更多詳細信息,請參見此常見問題解答

后綴運算符采用int作為參數,以將其與前綴運算符區分開。

后綴:

int operator--(int)
{
}

字首:

int operator--()
{
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM