2012-10-26 42 views
3

我已經成功的全部過載的一元++,--後綴/前綴運營商和我的代碼工作正常,但是當曾經在使用(++obj)++語句返回意外的結果元運算符在C++超載特例

這裏是代碼

class ABC 
{ 
public: 
    ABC(int k) 
    { 
     i = k; 
    } 


    ABC operator++(int) 
    { 
     return ABC(i++); 
    } 

    ABC operator++() 
    { 
     return ABC(++i); 
    } 

    int getInt() 
    { 
     return i; 
    } 
    private: 
    int i; 
}; 

int main() 
{ 
    ABC obj(5); 
     cout<< obj.getInt() <<endl; //this will print 5 

    obj++; 
    cout<< obj.getInt() <<endl; //this will print 6 - success 

    ++obj; 
    cout<< obj.getInt() <<endl; //this will print 7 - success 

    cout<< (++obj)++.getInt() <<endl; //this will print 8 - success 

     cout<< obj.getInt() <<endl; //this will print 8 - fail (should print 9) 
    return 1; 
    } 

有什麼解決方法或原因?

回答

1

我覺得最好在前增量方面實現後增量。

ABC operator++(int) 
{ 
    ABC result(*this); 
    ++*this; // thus post-increment has identical side effects to post-increment 
    return result; // but return value from *before* increment 
} 

ABC& operator++() 
{ 
    ++i; // Or whatever pre-increment should do in your class 
    return *this; 
} 
7

一般而言,預增量應返回ABC&,而不是ABC

你會注意到這會讓你的代碼無法編譯。修復相對容易(不要創建新的ABC,只需編輯現有的值,然後返回*this)。