2016-03-23 32 views
4

有人可以向我解釋爲什麼我的重載++(預版本)沒有更新值?片段是這樣的:重載++運算符不在C++中工作

circle circle:: operator++() 
{ 
    Area = Area * 2.0; 
    return *this; 
} 
///////////////////////////// 

int main() 
{ 
    class circle c1(4, 1, -1), c2(12, 4, 6); 
    c1.output(); 
    c1++; 
    c1.output(); 

    system("pause"); 
    return 0; 
} 
+4

你不是在調用postfix版本'c1 ++'嗎? – EdChum

+1

此外,您需要檢查您的[簽名](http://en.cppreference.com/w/cpp/language/operator_incdec),因爲您的版本不匹配 – EdChum

+0

增量後續簽名'c1 ++'需要您執行' circle&circle :: operator ++(int)'。你當前的'operator ++()'實現將用於預增'++ c1' – Vishal

回答

5

的你超載運營商的signature應該是:

circle& operator++(); // return by reference and this is prefix. 

但是你用postfix,所以它應該是:

circle operator++ (int); // int is unused 

更改簽名不夠,因爲你實現了一個前綴邏輯,直接更改值而不保存初始值。因此,如果您將Postfix運算符與您的實現一起用於像(c++).output()這樣的組合表達式,它將不會遵守預期的語義。

這裏的兩個版本的implemetnation:

circle& operator++() { // prefix 
    Area = Area * 2.0; // you can change directly the value 
    cout << "prefix"<<endl; 
    return *this;  // and return the object which contains new value 
} 

circle operator++ (int) { // postfix 
    circle c(*this);  // you must save current state 
    Area = Area * 2.0; // then you update the object 
    cout << "postfix"<<endl; 
    return c;   // then you have to return the value before the operation 
} 

而且這裏的online demo同時顯示之間的差異。

+1

是真的,但是這不會改變結果。 OP不直接使用表達式。該錯誤已在評論中突出顯示。 – juanchopanza

+0

不循環&運算符++();需要類或枚舉類型的參數? –

+0

@TaimurAhmed是的確是爲後綴增量。當你打字時,我正在完成我的答案。 – Christophe

7

這是因爲你超載前綴並調用後綴。您需要致電++c1;。要使用c1++;你需要重載後綴還有:

circle operator++ (int); 
+0

你可以更新你的答案,提及其他可能的修復? OP可能打算調用'c1 ++;' – quamrana

+0

是的,我應該這樣做。謝謝 – DimChtz

0

這裏是兩個版本的前綴和後修復。您可以添加一些代碼,以便撥打電話 c1 ++(1);(當然如果需要的話)

circle circle:: operator++() // prefix version 
{ 
    Area = Area * 2.0; 
    return *this; 
} 

circle& circle::operator++(int n) { //postfix version 
    if(n != 0)    // Handle case where an argument is passed. 
     //some code 
    else 
     Area = Area * 2.0;  // Handle case where no argument is passed. 
    return *this; 
} 


int main() 
{ 
    class circle c1(4, 1, -1), c2(12, 4, 6); 
    c1.output(); 
    c1++; 
    ++c1; 
    c1.output(); 

    system("pause"); 
    return 0; 
}