【发布时间】:2014-08-17 11:28:08
【问题描述】:
大家好,我正在研究一个 Thread 类和一个从 Thread 类继承的 CountingThread 类,包括使用库的同步计数器。但是在创建这个 CountingThread 类时,我遇到了“不允许不完整类型”的问题,所以如果你给我一些建议,如果我在一个糟糕的结构中形成这个 Thread 抽象类,或者说我在做什么错,我会很高兴. (仅供参考,我必须保留类和方法,因为这是一项任务)
#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;
}
【问题讨论】:
-
那行代码甚至应该做什么?函数调用不能是函数声明的一部分
-
“Thread 类和继承自 Thread 类的 CountingThread 类”——这是分配的要求吗?在现代 C++ 中,线程 API 不是根据类继承来设计的。看看C++11线程的设计就知道了(
std::thread和朋友们)。 -
不应该'virtual void main()=0;'在后代类中被覆盖?
-
以防万一这是您的问题(您的问题有点含糊......),在调用基类构造函数时,对象的实际类型(用于解析虚函数)是基类的!只是稍后,它才将其类型更改为派生类。不过,考虑一下 Chritian Hackl 的回答,您对这种方法根本没有帮助。
标签: c++ windows multithreading inheritance