3

我正在學習C++中的運算符重載。原始後綴++具有比賦值運算符優先級低的屬性。因此,例如,int i=0, j=0; i=j++; cout<<i<<j將輸出01.但是,當我重載後綴++時,此屬性似乎會丟失。C++運算符重載前綴/後綴

#include<iostream> 
using namespace std; 

class V 
{ 
public: 
    int vec[2]; 
    V(int a0, int a1) 
    { 
     vec[0]=a0;vec[1]=a1; 
    } 
    V operator++(int dummy) 
    { 
     for(int i=0; i<2; i++) 
     { 
      ++vec[i]; 
     } 
     V v(vec[0],vec[1]); 
     return v; 
    } 
    V operator=(V other) 
    { 
     vec[0]=other.vec[0]; 
     vec[1]=other.vec[1]; 
     return *this; 
    } 
    void print() 
    { 
     cout << "(" << vec[0] << ", " << vec[1] << ")" << endl; 
    } 
}; 

int main(void) 
{ 
    V v1(0,0), v2(1,1); 
    v1.print(); 

    v1=v2++; 
    v1.print(); 
} 

輸出(0,0)(2,2)而我期望(0,0)(1,1)。

你能幫助我理解爲什麼是這樣的,並恢復原來的財產的任何可能性?

+3

「原始後綴++的屬性優先於賦值運算符。」除非你是認爲低優先級比高優先級更強的人之一,否則這是錯誤的。後增量的優先級高於賦值的優先級,但後增量返回非增量值。 –

+0

感謝您澄清我的誤解,我用int i = 0,j = 0測試了這個問題; I =(j ++); COUT <<我<<焦耳;它輸出01.所以它不是優先級,而是返回機制。 – focusHard

回答

1

您需要複製vec[0]vec[1],然後再增加它們,而不是之後。那樣return v將返回原始值而不是遞增的值。

V operator++(int dummy) 
{ 
    V v(vec[0],vec[1]); 
    for(int i=0; i<2; i++) 
    { 
     ++vec[i]; 
    } 
    return v; 
} 
4

它打印(0,0)(2,2),因爲你的運營商++,不像內置的一個,返回V對象時,它後作用於遞增它,而不是之前的副本。

這是你的掌控,當你重載操作下,所以它是你的責任,使其行爲方式與相應的內置運營商在這方面。

這是你如何可以重寫你的運營商來實現這一目標:

V operator++(int dummy) 
{ 
    V v(vec[0],vec[1]); // Make a copy before incrementing: we'll return this! 
    for(int i=0; i<2; i++) 
    { 
     ++vec[i]; 
    } 
    return v; // Now this is *not* a copy of the incremented V object, 
       // but rather a copy of the V object before incrementing! 
} 

這裏是一個live example