我想寫一個抽象類與一些純粹的虛擬二元運算符,這應該由派生類實現以實現運算符多態性。這裏有一個簡單的例子:如何在抽象類中聲明重載運算符並在派生的非抽象類中重寫它?
class Base {
public:
virtual const Base& operator+ (const Base&) const = 0;
};
class Derived : public Base {
public:
const Derived& operator+ (const Derived&) const;
};
const Derived& Derived::operator+ (const Derived& rvalue) const {
return Derived();
}
不要緊,現在運營商做什麼,重要的部分是它返回:返回一個臨時的派生對象,或者對它的引用。現在,如果我嘗試編譯,我得到這個:
test.cpp: In member function ‘virtual const Derived& Derived::operator+(const Derived&) const’:
test.cpp:12:17: error: cannot allocate an object of abstract type ‘Derived’
test.cpp:6:7: note: because the following virtual functions are pure within ‘Derived’:
test.cpp:3:22: note: virtual const Base& Base::operator+(const Base&) const
怎麼了?是不是operator +(Base中唯一的純虛函數)被覆蓋? Derived爲什麼也應該是抽象的?
看起來它是因爲函數有不同的簽名的原則。 const const Derived&Derived :: operator +(const Derived&rvalue)const' vs'virtual const Base&Derived :: operator +(const Base&)const' –
順便說一句,您不能返回對臨時對象的引用,因爲referand的生存期是隻要函數返回就結束。 'operator +'需要按值返回,當調用者期望一個'Base'時,這會排除返回'Derived'。 –