gpt4 book ai didi

c++ - 没有对象不能调用成员函数 'virtual void ThreadBase::doTask()'

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:55 36 4
gpt4 key购买 nike

如何从 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();

}

你能告诉我该怎么做吗?谢谢。

最佳答案

将对 doTask 的调用更改为:

static_cast<ThreadBase*>(para)->doTask();

然后调用 pthread_create 到:

pthread_create( &thread_encoder, NULL, &ThreadEncoder :: run, this);

原因:当线程启动时,pthread_create 的第四个参数将作为参数传递给您的 ThreadBase::run 方法。

关于c++ - 没有对象不能调用成员函数 'virtual void ThreadBase::doTask()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40847107/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com