从父类调用纯虚函数

0 c++ class

我对c ++很新,但我想我明白发生了什么.父类试图在父类中调用纯虚拟成员函数.我认为通过覆盖子类中的虚函数,它会被调用.

我究竟做错了什么?

在parent.h中为我提供

class Parent
{
public:
virtual void run() = 0;
protected:
/** The function to starter routine and it will call run() defined by the
 * appropriate child class.
 * @param arg Arguments for the starter function
 */
static void * init (void * arg);
};
Run Code Online (Sandbox Code Playgroud)

我正在尝试在parent.cpp中执行此操作

void * Parent::init(void * arg)
{
  run();
}
Run Code Online (Sandbox Code Playgroud)

在我的child.h中我有这个:

class Child : public Parent
{public:
//...
virtual void run();
//...
};
Run Code Online (Sandbox Code Playgroud)

在child.cpp我有:

void Child::run()
{
   sleep(10);
}
Run Code Online (Sandbox Code Playgroud)

parent.cpp中的函数init无法编译.如何从父类调用派生函数?所有我的googleing只发现了关于不在子构造函数中调用虚函数的注释.

任何帮助都将不胜感激.

ito*_*son 11

run()是一个实例成员.Parent :: init是一个静态(类级别)成员.因此在init()实现中,没有可用于调用run()的实例(Parent Child).


Jus*_*ant 6

您正在尝试从静态方法调用实例方法.您需要更改init()为实例方法(通过删除static关键字),否则您将需要run()使用对象调用方法,例如obj->run()obj.run().