我有一个名为AbsAlgorithm的类,它具有三个纯虚函数,如下所示:

class AbsAlgorithm
{
public:
    //...other methods
    virtual void run() = 0;
    virtual bool init(TestCase&) = 0;
    virtual void done() = 0;
};


此类在我的可执行文件中,称为algatorc。最终用户必须创建algatorc项目,并且还必须实现这三种方法。但是问题是这样的:他还必须继承TestCase类。这是init方法中的参数。在我的主程序中,我必须编译用户编写的代码,并构建动态库并将其加载到我的程序中。我做到了问题是当我调用init方法时。

例:

用户创建一个名为Sorting的新algatorc项目。

因此,他以三节课结束:


SortingTestSetIterator
SortingTestCase
SortingAbsAlgorithm


在此SortingAbsAlgorithm中,他继承了AbsAlgorithm并实现了纯虚方法。在SortingTestCase中,他必须继承TestCase类,在SortingTestSetIterator中,他必须继承TestSetIterator并实现称为get_current()的方法,该方法返回TestCase

我的主程序将SortingTestSetIterator加载到TestSetIterator中,如下所示:

create_it = (TestSetIterator* (*)())dlsym(handle, "create_iterator_object");
TestSetIterator *it = (TestSetIterator*)create_it();


因此,现在,我可以调用类似TestSetIterator::get_current()的方法(此方法返回指向TestCase的指针,但用户返回SortingTestCase的对象)。但是,当我调用此方法时,结果是TestCase。没关系,但是接下来我需要将此传递给AbsAlgorithm::init(...)。当然,仍然没有问题,但是当用户实现方法init(...)时,他必须将其转换为子类(SortingTestCase)。这可能吗?

我知道这在Java中是微不足道的,但是我不知道如何在C ++中做到这一点。还是我定义方法TestCase* TestSetIterator::get_current()然后用户以某种方式重新定义此方法以使返回类型为SortingTestCase的一种方式?这样可以解决问题吗?

基本上,问题是这样的:

我有方法SortingTestSetIterator::get_current()返回指向SortingTestCase类实例的指针。那么,将父母转换为孩子是否可行?

最佳答案

如果要将父级转换为子级,只需编写以下代码:

child = dynamic_cast<Child*>(parent_object)


但是,为此,您的源类(父类)必须至少具有一个虚拟方法!它几乎肯定需要一个虚拟的析构函数,否则在尝试清理时会遇到问题...

关于c++ - 将父级转换为子级,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31705902/

10-10 13:21