我有一个抽象基类。从这个抽象基类派生出很多抽象类
#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()。 如何解决这个问题 Abstract Derived classes如何看到这个新方法
我想到的一个解决方案是:-
我需要扩展 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
,它继承了 OtherBase
和 Derived1
的方法:
#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;
}
}
关于c++ - 在不破坏现有基类的情况下向具有许多派生类的抽象基类添加新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68072268/