2014-03-05 39 views
0
// The following operator++() represents overloading of pre-increment 
MyIncrDecrClass& operator++() 
{ 
    ++this->m_nCounter; 
    return *this; 
} 

// Passing dummy int argument is to mention overloading of post-increment 
MyIncrDecrClass& operator++(int) 
{ 
    this->m_nCounter++; 
    return *this; 
} 

因此,這是怎樣一個崗位和預增操作符來實現,但對我來說,我不能真正實現它這樣的,所以這是我做過什麼:後增量重載中的冗餘?

VLongInt& VLongInt::operator++() 
{ 
    ... //BUILD TEMP vector 
    this->vec = temp; 
    return *this; 
} 

VLongInt& VLongInt::operator++(int) 
{ 
    this->vec = this.vec; //seems unnecessary 
    ... //BUILD TEMP vector 
    this->vec = temp 
    return *this; 
} 

這有什麼錯?看起來兩者應該以同樣的方式實施。只有頭文件應該不同,對吧?

+0

這聽起來像你的代碼的工作,你只是想知道,如果你寫的是錯誤的。這可能更適合http://codereview.stackexchange.com/ –

+1

這一切都取決於您希望增量操作員爲您的班級表示什麼。但它看起來對我來說是錯誤的 - 無論哪種方式你的論點都應該修改 - 但是在一種情況下,你應該返回原始的,而不是修改後的版本。而且你不區分功能簽名 - 這甚至編譯? – Floris

+1

在第二個代碼塊中,您編寫了兩個具有相同名稱,返回類型和參數的函數。也許我對C++不夠了解,但編譯器應該如何區分這兩個定義? –

回答

2

你的postincrement操作符重載的例子是錯誤的。

// Passing dummy int argument is to mention overloading of post-increment 
MyIncrDecrClass& operator++(int) 
{ 
    this->m_nCounter++; 
    return *this; 
} 

Intsead應該有

// Passing dummy int argument is to mention overloading of post-increment 
MyIncrDecrClass operator ++(int) 
{ 
    MyIncrDecrClass tmp(*this); 

    ++this->m_nCounter; 

    return tmp; 
} 

也是你的問題是完全不清楚。您事實上定義了相同的運算符兩次

VLongInt& VLongInt::operator++() 
{ 
    //... 
    return *this; 
} 

VLongInt& VLongInt::operator++() 
{ 
    //... 
    return *this; 
} 

我沒有看到區別。此外,你沒有顯示你的班級定義,因此沒有什麼可以說你的問題。它是未知的。

至少如你所說自己你的postincrement操作符應聲明int類型的虛擬參數。它必須返回一個臨時對象。

VLongInt VLongInt::operator ++(int) 

const VLongInt VLongInt::operator ++(int) 
+0

對不起,它應該是:VLongInt&VLongInt :: operator ++(int) – user2967016

+0

@ user2967016這是一個錯誤的聲明,因爲您返回對象本身。所以你的後增量和增量前的運算符沒有區別。 –

+1

好吧,我應該做這樣的事情? this = original; ... this-> vec = temp ... return original ???? – user2967016

0

有什麼不對嗎?

是的,你的代碼違反了ODR(一個定義規則)。它在§3.2/1中定義爲:

任何翻譯單元都不得包含任何變量,函數,類類型,枚舉類型或模板的多個定義。

而應該定義這兩個功能:

VLongInt& VLongInt::operator++(); 
const VLongInt VLongInt::operator++(int); 

具體來說,請注意,後增量操作返回值應該是const TT(與T是你的類型)。

+0

是否真的有必要(可能會改變輸出的東西),或者如果我想成爲一名專業程序員,我應該做些什麼? – user2967016

+1

@ user2967016,如果你想編寫好的代碼,這是必要的。 – Shoe