通常,必须在Child类中重写callBack()。
但事实并非如此。当线程调用callBack()时,它运行原始方法。
有没有办法解决这个问题?
我用“g ++ -o file source.cpp -lpthread”
编译了它我确定它与编译器无关。
#include <iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;
class Parent
{
public:
virtual void callBack()
{
cout << "Original callBack() reported this: " << this << endl;
}
private:
pthread_t th = 0;
static void *th_func(void *arg)
{
Parent *p = (Parent*)arg;
cout << "*th_func() reported *arg: " << arg << endl;
p->callBack();
}
public:
Parent()
{
if(pthread_create(&th, NULL, th_func, (void*)this) < 0)
cerr << "thread not born." << endl;
else
cout << "thread has born." << endl;
}
~Parent()
{
if(th!=0)
pthread_join(th, NULL);
cout << "joined. Parent leaving." << endl;
}
};
class Child : public Parent
{
public:
void callBack()
{
cout << "child overridden." << endl;
}
Child() : Parent(){}
};
int main()
{
Child *ch = new Child();
delete ch;
return 0;
}