2012-06-27 51 views
6

我想超載operator==,但是編譯器拋出以下錯誤:重載==操作符抱怨「必須只有一個參數」

‘bool Rationalnumber::operator==(Rationalnumber, Rationalnumber)’ must take exactly one argument 

我的一小段代碼如下:

bool Rationalnumber::operator==(Rationalnumber l, Rationalnumber r) { 
    return l.numerator() * r.denominator() == l.denominator() * r.numerator(); 
} 

聲明:

bool operator==(Rationalnumber l, Rationalnumber r); 

沒有人有,爲什麼它拋出牛逼任何想法他錯誤?

+1

這可能有助於:http://stackoverflow.com/questions/4421706/operator-overloading。既然你是一個成員,它已經讓左側通過隱藏的'this'參數隱式進入。 – chris

+1

您必須用一個ar定義成員函數gument或帶兩個參數的文件範圍函數。 – harper

+0

它是會員功能還是獨立功能? –

回答

1

您應該將您的operator ==從RationalNumber中移除到其他地方。 因爲它是在一個類中聲明的,所以認爲'this'是第一個參數。從語義上看,你可以向編譯器提供3個參數。

12

如果operator==是一個非靜態數據成員,是應該只有一個參數,作爲比較將是隱式this參數:

class Foo { 
    bool operator==(const Foo& rhs) const { return true;} 
}; 

如果你想使用免費的運營商(即不是一個類的成員),那麼你可以指定兩個參數:

class Bar { }; 
bool operator==(const Bar& lhs, const Bar& rhs) { return true;} 
2

作爲成員運算符重載它應該只有一個參數,另一個是this

class Foo 
{ 
    int a; 

public: 
    bool operator==(const Foo & foo); 
}; 

//... 

bool Foo::operator==(const Foo & foo) 
{ 
    return a == foo.a; 
} 
0
friend bool operator==(Rationalnumber l, Rationalnumber r); 

你把它聲明爲非成員函數,它可以採取兩個參數。當您將其聲明爲成員函數時,它只能使用一個參數。

0

如果要聲明一個const SpreadSheetCell &運營商+(常量SpreadSheetCell & LHS,常量SpreadSheetCell &右);那麼第一個參數就是一個「this」指針。因此,拋出一個錯誤爲」

錯誤: '常量SpreadSheetCell & SpreadSheetCell ::運算符+(常量SpreadSheetCell &,常量SpreadSheetCell &)' 必須採取零個或一個參數

如果你想擁有一個。兩個參數函數,那麼你必須在類之外聲明相同的函數並使用它

相關問題