2010-08-27 33 views
2

我想重載我的操作符它真的只是一個類,它包含算術函數和一個數組變量序列。二進制'*':沒有找到全局運算符,它需要類型'統計'(或沒有可接受的轉換)

但是當我我的過載(*)乘法算我得到這個錯誤:

 binary '*' : no global operator found which takes type 'statistician' 
(or there is no acceptable conversion) 

這發生在我的代碼試圖做的事:s = 2*u;在main.cpp中

其中s和u是統計學課程。

統計學家=我的課

(statistician.h)

class statistician 
{ 
... other functions & variables... 

const statistician statistician::operator*(const statistician &other) const; 

..... more overloads... 

}; 

任何幫助將是真棒謝謝!

回答

5

聲明命名空間範圍operator*,這樣你也可以有一個敞篷操作上右手邊是statistician類型的不行。

statistician operator*(const statistician &left, const statistician &right) { 
    // ... 
} 

不用說,你應該刪除的課堂之一,那麼,你需要一個轉換構造函數取int

4

這正是爲什麼二元運算符如*或+應該是非成員。

如果你沒有s = u * 2,它會工作,假設你有statistician接受單個int參數非顯式構造。但是,2 * u不起作用,因爲2不是statistician,而int不是成員operator*的類。

對於這個工作吧,你應該定義一個非成員operator*,並使其成爲friendstatistician的:


statistician operator*(const statistician &left, const statistician &right); 

您還需要可以定義取整數(或任何其他的operator*其他版本您希望能夠「相乘」的類型)或爲statistician定義非顯式構造函數以啓用隱式轉換。

相關問題