我正在尝试使用一些纯虚拟二元运算符编写一个抽象类,它应该由派生类实现以实现运算符多态性。这是一个简化的示例:
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();
}
操作符现在做什么并不重要,重要的是它返回什么:它返回一个临时的 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 也应该是抽象的?