在基类函数中使用此函数访问派生类成员函数,其中函数在派生类中重写

时间:2014-10-09 17:43:05

标签: c++

-------------common/cthread.h----------------
#include<iostream>
using namespace std ;
#include<string.h>
#include<pthread.h>
#include<stdio.h>
#include<errno.h>

namespace Framework
{
class CThread
{
 public:
 CThread(void)
 {
 }
 virtual ~CThread(void)
 {
 }
 void Execute() ;
 virtual unsigned int Run(void ) = 0 ;
 static unsigned int ThreadRun(void *obj) ;

 protected:
 pthread_t thread_obj ;

 private:
 int thread_ret_value ;
};
}
-----------common/cthread.cc----------------
#include "cthread.h"

namespace Framework
{

void *(*threadRun) (void*) = reinterpret_cast <void *(*) (void *)> (CThread::ThreadRun) ;
//int CThread::value_part = 20 ;

void CThread::Execute()
{
    cout<<endl<<"["<<__FILE__<<":"<<__LINE__<<"] "<<"Initializing CThread...";
    try
    {
        thread_ret_value = pthread_create(&thread_obj, 0, threadRun, this) ;
        if(thread_ret_value)
        {
            cout<<"["<<__FILE__<<":"<<__LINE__<<"] "<<"Thread could not be created : "<<strerror(thread_ret_value);
            fprintf(stderr,"Error - pthread_create() return code: %d\n",thread_ret_value);
        }
        else
            pthread_join(thread_obj, NULL) ;
    }
    catch(exception& e)
    {
        cout<<endl<<"["<<__FILE__<<":"<<__LINE__<<"] "<<"Exception Occured in ["<<__FILE__<<":"<<__LINE__<<"] "<<e.what() ;
    }
    cout<<endl<<"["<<__FILE__<<":"<<__LINE__<<"] "<<"Exiting CThread...";
}

unsigned int CThread::ThreadRun(void *obj)
{
    int ret_status = 0 ;
    cout<<endl<<"["<<__FILE__<<":"<<__LINE__<<"] "<<"Started CThread...";
    CThread *pthread = (CThread*) obj ;
    cout<<"\nRunning CThread..." ;
    pthread->Run() ;
    cout<<"\nStopped CThread..." ;
}

------------------dispatcherthread.h------------------------
#include<iostream>
using namespace std ;

#include "common/cthread.h"
using namespace Framework ;

class Dispatcherthread: public CThread
{

    public:
    Dispatcherthread()
    {
        cout<<"\nConstructor Dispatcherthread Called." ;
    }
    //static int nuThread ;
    void Initialize() ;
    virtual unsigned int Run() ;
    void aman() ;
    int *dispatcherImp();
    void stop() ;
};
-------------------dispatcherthread.cc-------------------
#include"dispatcherthread.h"

void Dispatcherthread::Initialize()
{
    cout<<endl<<"["<<__FILE__<<":"<<__LINE__<<"] "<<"Initializing Dispatcher Thread...";
}

unsigned int Dispatcherthread::Run()
{
    cout<<"\nThread started.";
/// for(int i=0; i<=10; i++)
///     cout<<"\nThread is running : "<<i ;
    cout<<"\nThread stopped.";
}
---------------------------------------------------------------

我遇到了分段错误:common / thread.cc:36(“this”无法在派生类中覆盖访问函数)。请帮帮我。我知道一些事情&gt;非常基本是错的。如果我在同一个文件或命名空间中编写这两个类,它就可以工作。

1 个答案:

答案 0 :(得分:0)

这一行是个问题。

void *(*threadRun) (void*) = reinterpret_cast <void *(*) (void *)> (CThread::ThreadRun) ;

您正在使用一个应该返回int并将其强制转换为返回void的函数的函数。这些函数类型的堆栈结构很可能是不同的。