2009-10-16 62 views
0

我对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); 
}; 

我试图做到这一点在parent.cpp

void * Parent::init(void * arg) 
{ 
    run(); 
} 

在我child.h提供给我,我有这样的:

class Child : public Parent 
{public: 
//... 
virtual void run(); 
//... 
}; 

而在child.cpp我有:

void Child::run() 
{ 
    sleep(10); 
} 

parent.cpp中的函数init是无法编译的地方。我如何从父类调用派生函数?我所有的googleing都只提出了有关在子构造函数中不调用虚函数的注释。

任何帮助都将不胜感激。

+0

看看您的问题在这里得到解答:http://www.parashift.com/c++- faq-lite/virtual-functions.html – Artelius 2009-10-16 22:49:32

回答

10

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

5

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

2

您是否知道arg的实际类型:它实际上是Parent实例吗?如果是这样,那么...

void Parent::init(void* arg) 
{ 
    Parent* self = static_cast<Parent*>(arg); 
    self->run(); 
} 
+0

我认为这解决了我的问题。我从pthread_create调用init,并控制了作为参数传递给函数的内容,但完全不知道要传入什么。谢谢!我从来不会想到我自己。 – 2009-10-16 23:34:00

+1

是的,它是C++'Thread'类的典型实现。 – ChrisW 2009-10-16 23:41:41

0

看看这个例子,我最近提供here

/** calls thread_func in a new thread passing it user_data as argument */ 
thrd_hdl c_api_thread_start(void (*thread_func)(void*), void* user_data); 

/** abstract thread base class 
* override my_thread::run to do work in another thread 
*/ 
class my_thread { 
    public: 
    my_thread() hdl_(c_api_thread_start(my_thread::thread_runner,this)) {} 
    // ... 

    private: 
    virtual int run() = 0; // we don't want this to be called from others 

    thrd_hdl_t hdl_; // whatever the C threading API uses as a thread handle 

    static int thread_runner(void* user_data) 
    { 
     my_thread* that = reinterpret_cast<my_thread*>(user_data); 
     try { 
     return that->run(); 
     } catch(...) { 
     return oh_my_an_unknown_error; 
     } 
    } 
};