在不破坏现有基类的情况下,向具有许多派生类的抽象基类添加新方法



我有一个抽象基类。从这个抽象基类派生出许多抽象类

#if ABI_VERSION_ATLEAST1
class Base
{
public:
virtual void food() =0
};
#endif

例如

#if ABI_VERSION_ATLEAST1
class Derived1: public Base
{
};
#endif

假设我想在不破坏二进制兼容性的情况下向它添加新方法。唯一的方法是扩展此类

#if ABI_VERSION_ATLEAST2
class Base_Ext : public Base
{
public:
virtual void food1()=0;
};
#endif

问题是已经存在的派生类实现无法访问此food1((。如何解决这个问题抽象派生类如何看到这个新方法

我脑海中的一个解决方案是:-

我需要延长Derived1……

#if ABI_VERSION_ATLEAST2
class Derived2 : public Derived1, public Base_Ex
{ 
} ;
#endif 

再次在这里解决钻石问题,我将不得不更改

class Derived1: public Base to
class Derived1: public virtual Base {} 

这是我不想做的,因为它会再次破坏现有派生类的二进制兼容性。所以坚持

您可以创建第二个基类,将其命名为OtherBase,在其中您可以添加新方法。您可以创建新的派生类,将其命名为Derived2,它继承了OtherBaseDerived1:的方法

#include <iostream>
class Base
{
public:
virtual void food() = 0;
virtual ~Base() {}; // virtual destructor is necessary to avoid memory leak
};
class Derived1 : public Base
{
public:
virtual void food() override
{
std::cout << "Derived1::food" << std::endl;
}
virtual ~Derived1() override {}
};
class OtherBase
{
public:
virtual void food1() = 0;
virtual ~OtherBase() {}; // virtual destructor is necessary to avoid memory leak
};
class Derived2 : public OtherBase, public Derived1
{
public:
virtual void food1() override
{
std::cout << "Derived2::food1" << std::endl;
}
virtual ~Derived2() override {}
};
int main()
{
std::cout << "On the stack:" << std::endl;
Derived2 derived2;
derived2.food();
derived2.food1();

std::cout << "On the heap:" << std::endl;
OtherBase * otherBase_p1 = new Derived2();
if (otherBase_p1) // check if memory was is allocated
{
otherBase_p1->food1();

Base * base_p = dynamic_cast<Base *>(otherBase_p1);
if (base_p) // if dynamic_cast was unsuccessful than base_p is nullptr
{
base_p->food();
}

delete otherBase_p1;
}
}

最新更新