2017-04-11 35 views
3

我是C++的初學者,編碼時遇到一個奇怪的代碼,下面是問題。使用遞減運算符編寫C++代碼時的奇怪行爲

class INT 
{ 
    friend ostream& operator<<(ostream& os, const INT &i); 

public: 
    INT(int i) :m_i(i){}; 
    INT(const INT& i) 
    { 
     m_i = i.m_i; 
    } 
    INT& operator++() 
    { 
     ++(this->m_i); 
     return *this; 
    } 
    const INT operator++(int) 
    { 
     INT temp = *this; 
     ++(*this); 
     return temp; 
    } 
    INT& operator--() 
    { 
     --(this->m_i); 
     return *this; 
    } 
    const INT& operator--(int) 
    { 
     INT temp = *this; 
     --(*this); 
     return temp; 
    } 
    int& operator*() const 
    { 
     return (int&)m_i; 
    } 
private: 
    int m_i; 
}; 

ostream& operator<<(ostream& os, const INT &i) 
{ 
    os << "[" <<i.m_i<< "]"; 
    return os; 
} 

int main(int argc, char* argv[]) 
{ 
    INT i(5); 
    cout << i++; 
    cout << ++i; 
    cout << (i--); 
    cout << --i; 
    cout << *i; 
} 

我得到的結果

[5][7][-858993460][5]5 

我預期的結果是

[5][7][7][5]5 

我使用Visual Studio 2013年。非常感謝您!

回答

6
const INT& operator--(int) { ... } 

是錯誤的。您正在返回對函數範圍內的對象的引用。函數返回後引用變爲無效。將其更改爲:

INT operator--(int) { ... } 

雖然它,你不需要const在:

const INT operator++(int) { ... } 

將其更改爲:

INT operator++(int) { ... } 
+0

任何想法,爲什麼它沒有失敗對於返回'INT&'的'++'運算符也是如此。因爲他們都是UB,所以只是愚蠢的運氣? – Barmar

+0

@Barmar OP的帖子中的'++'操作符返回一個'const INT',而不是'const INT&' –

+0

@king_nak對,我看的是錯誤的。 – Barmar