abstract base class 以自身为参数的虚纯方法
Abstract base class virtual pure method that takes itself as a parameter
抱歉措辞不当,我不太确定如何表达这个问题。
我有一个基础 class A,它有一个纯虚拟运算符 +=,它采用自身的一个实例。在派生的 class B 中,我想重写基础 class 的 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 派生的任何 class 都将实现 operator+= ,其中它将派生的 class 的实例作为参数。
virtual operator+=(const <this_class_type>&) = 0;
请问您能提供解决方案吗?非常感谢!
实现此目的的一种方法是使用 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
}
抱歉措辞不当,我不太确定如何表达这个问题。
我有一个基础 class A,它有一个纯虚拟运算符 +=,它采用自身的一个实例。在派生的 class B 中,我想重写基础 class 的 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 派生的任何 class 都将实现 operator+= ,其中它将派生的 class 的实例作为参数。
virtual operator+=(const <this_class_type>&) = 0;
请问您能提供解决方案吗?非常感谢!
实现此目的的一种方法是使用 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
}