<Windows.h> c++ 线程和继承

<Windows.h> c++ threads and inheritance

本文关键字:线程 继承 c++ lt Windows gt      更新时间:2023-10-16

大家好,我正在研究一个线程类和一个CountingThread类,从线程类继承,包括使用库的同步计数器。但是在创建这个CountingThread类时,我遇到了一个"不允许不完整类型"的问题,所以如果你给我一些建议,如果我在一个糟糕的结构中形成这个线程抽象类,或者说我做错了什么,我会很高兴。(仅供参考,我必须保持类和方法,因为它是一个分配)

#ifndef _THREAD_H_
#define _THREAD_H_
#include <Windows.h>
#include <iosfwd>
class Thread{
private:
    HANDLE hThread;
    int idThread;
public:
    Thread(LPTHREAD_START_ROUTINE fnct){  // here I'm trying to get a function and create thread with it
        hThread = CreateThread(NULL, 0,fnct,NULL,0,(LPDWORD)&idThread);
    }
    virtual void main()=0;
    void suspend(){
        SuspendThread(hThread);
    }
    void resume(){
        ResumeThread(hThread);
    }
    void terminate(){
        TerminateThread(hThread,0);
    }
    static void sleep(int sec){
        Sleep(sec*1000);
    }
};

#endif 

CountingThread.h

#ifndef _COUNTINGTHREAD_H_
#define _COUNTINGTHREAD_H_
#include "SynchronizedCounter.h"
#include "Thread.h"
class CountingThread :public Thread{
private:
    SynchronizedCounter counter;
public:
    CountingThread(counter.increment()){   // here I'm having the error "incomplete type on counter"
    }    // I want to create thread with the counter.increment function
};
#endif

SynchronizedCounter.h

#ifndef SYNCHRONIZEDCOUNTER_H_
#define SYNCHRONIZEDCOUNTER_H_
#include "Mutex.h"
#include <iosfwd>
class SynchronizedCounter{
private:
    int count;
public:
    SynchronizedCounter();
    SynchronizedCounter(int);
    void increment();
    int value();
    friend std::ostream &operator <<(std::ostream& output, const SynchronizedCounter& counter)
    {
        output << counter.count << endl;
        return output;
    }
};
#endif

和synchronizedCounter::increment

void SynchronizedCounter::increment(){
    Mutex mut;
    mut.lock;
    count++;
    mut.unlock;
}

似乎是语法错误。你应该在这里定义一个参数:

所以应该是:

class CountingThread :public Thread{
private:
    SynchronizedCounter counter;
public:
    CountingThread()
        {
        counter.increment())
         //... etc
        }    // I want to create thread with the counter.increment function
//...
};

无论如何counter.increment()返回void,你不能把它作为参数传递。