重複的:"pure virtual method called" when implementing a boost::thread wrapper interface提升線程破壞多態性
我試圖創建一個使用升壓線程的線程更多的面向對象版本。
所以我創建了一個Thread類:
class Thread {
public:
Thread() {}
virtual ~Thread() { thisThread->join(); }
void start() { thisThread = new boost::thread(&Thread::run, this); }
virtual void run() {};
private:
boost::thread *thisThread;
};
這個類中創建啓動線程() 這樣的:
thisThread = new boost::thread(&Thread::run, this);
的問題是,當我創建一個類,覆蓋run()
方法,從Thread的run()
方法是由線程調用而不是新的run()
方法
,比如我有繼承Thread類:
class CmdWorker: public Thread {
public:
CmdWorker() : Thread() {}
virtual ~CmdWorker() {}
void run() { /* deosn't get called by the thread */ }
};
當我做
Thread *thread = new CmdWorker();
thread.start(); //---> calls run() from Thread instead of run() from CmdWorker
但爲了更加清晰:
thread.run(); calls the correct run from CmdWorker, (run() is virtual from Runnable)
任何想法,爲什麼出現這種情況或如何修復?
注: 我創建了一個函數(即具有無關Thread類)
void callRun(Thread* thread) {
thread->run();
}
,改變了線程創建於:
thisThread = new boost::thread(callRun, this);
當調試我注意到thread
指針指向Thread類型的對象而不是CmdWorker
編輯:
測試用例代碼爲:http://ideone.com/fqMLF 和http://ideone.com/Tmva1
對象似乎切片(但是這是奇怪的,因爲使用指針)
沒能提振添加到它
這個問題我不清楚! – Nawaz
代碼不足。我看不出你會如何使用這種構造。 –
FYI'std :: thread'即將到達。無論如何,boost :: thread'究竟有什麼問題? – spraff