2015-07-03 26 views
0

以下代碼將退出執行過程。oop操作符重載未返回正確的值

有些想法?

我在想,t1不等於t2,所以我試圖按字節t1和t2複製字節。但那並沒有奏效。

#include<stdio.h> 
class test{ 
    int x; 
public: 
    test(){ x=1; } 
    bool operator==(test &temp); 

}; 

bool test::operator==(test &temp){ 
    if(*this==temp){ 
     printf("1"); 
     return true; 
    } 
    else{ 
     printf("2"); 
     return false; 
    } 


} 
void main(){ 
    test t1, t2; 
    t1==t2; 

} 

回答

0

此行

if (*this == temp){ 

電話operator==了,所以我們最終堆棧溢出。

也許你的意思是

if (this == &temp){ // & 

你必須決定是什麼意思,該班是相等的。上面的這一行假定一個類只等於它自己。但是,例如,如果將類定義爲相等,如果它們具有相同的值,則可以編寫

bool test::operator==(test &temp){ 
if (this->x == temp.x){ 
    printf("1"); 
    return true; 
} 
else{ 
    printf("2"); 
    return false; 
}