2016-11-08 79 views
-1

看到這個非常簡單的代碼:==操作符()循環永遠

struct A 
{ 
    bool operator ==(const int &t) 
    { 
     return *this == t; 
    } 
}; 
void main() 
{ 
    A p; 
    p == 2;// this code loops for ever!!! 
} 

劑量任何一個知道爲什麼代碼循環永遠! 實際上運算符==()會遞歸地調用它自己!
非常感謝

+3

因爲'* this == t'與'p == 2' =>調用操作符'=='在左邊的struct A和右邊的int之間 – Garf365

+0

提示:執行'* this時會發生什麼== t'? – milleniumbug

+2

'* this == t'等於'this.operator ==(t)'。 – Yves

回答

5

問問你自己。

什麼是*this?這是struct A

那麼什麼是*this == t?它基本上是A::operator==()與參數t。

您正在調用相同的功能。

+0

有時調試你的程序! – alirakiyan