0

我不知道这是否可能,但我有一个想法,即创建一个抽象类来使用 WinAPI 创建线程。该类将由定义要在线程中执行的函数的类继承。

我有两节课:

class XYZ{
//...

class ABC: public XYZ{
//...

我有一个构造

ABC::ABC()
{
    addThread(this,1);
}

addThread 在 XYZ 类中定义:

void addThread(void* self, int a)
{
    DWORD ThreadID;
    THREAD_DATA *threadData;
    threadData->self = self;
    threadData->thread_id = a;
    CreateThread(NULL, 0, createThread, threadData, 0, &ThreadID);
}

如您所见,我正在创建一个包含两个字段的结构:超类的对象和线程数(因此该方法可以知道使用哪些数据)。

这是结构的样子:

typedef struct _THREAD_DATA {
void*       self;
int     thread_id;
} THREAD_DATA;

XYZ 类的静态方法中的 createThread:

static DWORD WINAPI createThread(void* _threadData)
{
    THREAD_DATA* threadData = (THREAD_DATA*) _threadData;
    return threadData->self->execute(threadData->thread_id);
}

And here is the place where everything goes wrong. My VSC++ 2010 is underlining the first word "threadDataself" in the second line of the static method body. After compilation I get an error:

left of '->execute' must point to class/struct/union/generic type

I have no idea how to fix it. I wrote this code using those links: http://goo.gl/7VYC3 & http://goo.gl/ETfe7

The execute method is decalared in the XYZ class as:

virtual DWORD execute(int i);

and then defined in the ABC class as

DWORD ABC::execute(int i){
//...

Can anyone please help me? I would appreciate any tips how to make this works.

4

2 回答 2

2

"self" is defined as a void pointer, and you are trying to call the "execute" method on it, which does not exist. you need to change the type of self to the base class that contains the method "execute."

Like this:

typedef struct _THREAD_DATA {
    XYZ*       self;
    int     thread_id;
} THREAD_DATA;

When attempting to call an overridden method polymorphically as you are here, you must make sure the type of the object you are calling the method on is the base class type. You cannot use a void pointer.

于 2012-10-23T21:34:32.240 回答
1

One obvious error for you to fix:

THREAD_DATA *threadData;
threadData->self = self;
threadData->thread_id = a;

here threadData is a pointer with no value assigned, and then you use is as a valid pointer. You need to change it to

THREAD_DATA *threadData = new THREAD_DATA();

and somehow manage its life time, ie. delete it inside thred function on its end.

于 2012-10-23T21:58:12.473 回答