我有下面的類表示數值陣列繼承和操作符重載
class Array {
protected :
double *data; // this will hold the data of the array
int n; // number of elements in the array
public :
virtual Array operator+ (double value) const {
// return a new array with the argument added to each element
}
// other declarations follow here...
};
和另一類與前一個繼承和添加的布爾掩碼的每個元素
class MaskedArray : public Array {
private :
bool *mask; // this holds the boolean mask of the array
public :
MaskedArray operator+ (double value) const {
// return a new MaskedArray with the argument added to each element
}
// other declarations follow here...
}
「無效協變返回類型」的錯誤
當我嘗試編譯時,我得到錯誤「invalid covariant return type」,這是正常的,因爲兩個類中的兩個重載運算符具有相同的簽名。
我能夠通過引用繼承類的重載操作符的參數而不是通過值來繞過這個問題,因爲這改變了函數的簽名,同時保持兩個類的接口。但我覺得這不是很乾淨,如果我想從MaskedArray繼承,該怎麼辦?我會面臨同樣的問題。
我希望能夠寫出這樣的東西在我的客戶端代碼
Array array;
// populate array here
Array array2 = array + 1.0;
MaskedArray maskedArray;
// populate maskedArray here
MaskedArray maskedArray2 = maskedArray + 1.0
有另一種更優雅的方式比我的「黑客」來實現這一目標?
如果基類函數是虛擬的,那麼只應該得到關於「無效協變返回類型」的錯誤。你確定這是給你錯誤的_exact_代碼嗎? –
順便說一句,繼承真的是'Array'和'MaskedArray'的正確關係嗎? 'Array'的掩蔽附加函數會更好嗎?從概念上講,一個'MaskedArray'不能替代'Array',並且實際上這兩個工作都是一個好主意?數組x = static_cast(maskedArray)+ 5.0;'和'Array y = maskedArray + 5.0;' –