抽象基类虚拟纯方法,以自身为参数

时间:2018-03-21 12:25:42

标签: c++ inheritance c++17 virtual-method abstract-base-class

对任何不好的措辞道歉,我不太清楚如何表达这个问题。

我有一个基类A,它有一个纯虚拟运算符+ =,它接受一个自己的实例。在派生类B中,我想覆盖基类的operator + =,使得它采用B的实例(而不是A)。

// Abstract base class
template <class T>
class A
{
    A() = default;

    virtual A<T>& operator+=(const A&) = 0;
}

// Derived class
template <class T>
class B : public A<T>
{
   T some_field = 3.14159;

   B(const T x) : A(), some_field(x) {}

   B<T>& operator+=(const B& b) override
   {
       this.some_field += b.some_field;

       return (*this);
   }
}

我明白为什么这不起作用;这两种方法是不同的函数,因为它们期望不同的参数。但是,我假设必须有某种方法来保证从A派生的任何类都将实现operator + =,其中它将派生类的实例作为参数。

virtual operator+=(const <this_class_type>&) = 0;

请问您能解决这个问题吗?非常感谢!

1 个答案:

答案 0 :(得分:3)

实现此目的的一种方法是使用T作为参数:

template<typename T>
class IBase
{
public:
    virtual IBase& operator+=(const T& Instance) = 0;
};

class CDerived : IBase<CDerived>
{
public:
    IBase& operator+=(const CDerived&) override
    {
        return *this;
    }
};

class COtherDerived : IBase<COtherDerived>
{
public:
    IBase& operator+=(const COtherDerived&) override
    {
        return *this;
    }    
};

int main(int argc, char** argv)
{
    CDerived Derived1, Derived2;
    Derived1 += Derived2;
    COtherDerived Derived3;
    // Derived3 += Derived1; <-- Will not compile
}