如何在ThreadBase.h中调用虚函数以在pthread_create中运行的静态指针函数中使用它?
当我遵守它时,显示 - > "无法调用成员函数' virtual void ThreadBase :: doTask()'没有对象"
非常感谢你。
// ThreadBase.h
class ThreadBase {
public:
ThreadBase();
void sayName();
virtual void doTask() = 0; // --> dotask()
static void *run( void *para );
void start();
};
// ThreadBase.cpp
#include <iostream>
#include "ThreadBase.h"
#include "ThreadEncoder.h"
#include "pthread.h"
using namespace std;
ThreadBase :: ThreadBase()
{
}
void ThreadBase :: sayName() {
cout << "I am a RobnertsQ" << endl;
}
void *ThreadBase :: run( void *para ) {
cout << "run()" << endl;
while( false ) {
doTask(); // -> ***My problem
// ( delaySleep )
}
}
void ThreadBase :: start() {
pthread_t thread_encoder;
pthread_create( &thread_encoder, NULL, &ThreadEncoder :: run, NULL);
}
// ThreadEncoder.h
#include <iostream>
using namespace std;
class ThreadEncoder : public ThreadBase {
public:
ThreadEncoder();
ThreadEncoder( int );
void doTask();
protected:
string getFullName() {
return "ThreadEncoder";
}
};
// ThreadEncoder.cpp
#include <iostream>
#include "ThreadBase.h"
#include "ThreadEncoder.h"
using namespace std;
ThreadEncoder :: ThreadEncoder()
{
cout << "ThreadEncoder default " << endl;
}
ThreadEncoder :: ThreadEncoder( int delaySleep )
{
cout << "ThreadEncoder delaySleep = " << delaySleep << endl;
}
void ThreadEncoder :: doTask() {
cout << "ThreadEncoder doTask !!!" << endl;
// main.cpp
#include <iostream>
#include "ThreadBase.h"
#include "ThreadEncoder.h"
//#include "ThreadGps.h"
using namespace std;
int main(){
ThreadEncoder te;
te.start();
}
你可以告诉我该做什么吗?
感谢。
答案 0 :(得分:0)
将对doTask的调用更改为:
static_cast<ThreadBase*>(para)->doTask();
调用pthread_create到:
pthread_create( &thread_encoder, NULL, &ThreadEncoder :: run, this);
原因:当线程启动时,pthread_create的第四个参数将作为参数传递给ThreadBase :: run方法。