从函数指针向量调用成员函数的函数指针

时间:2013-01-01 16:25:19

标签: c++ vector function-pointers event-driven-design

我认为这主要是语法错误(虽然在编译期间未捕获,但仅在运行时发生错误)

我正在尝试开发一个事件驱动的架构,我在其中保留了eventReceiver的向量,并尝试从向量中调用它们。

CommonIO.h

    class CommonIO {
    public:
        typedef void (*incomingMsgReceiver)(char*);
            void registerForIncomingMsg(incomingMsgReceiver);
            void incomingMsgReceived(char*);
    }

CommonIO.cpp

    std::vector<void (*)(char*)> listeners;

    void CommonIO::registerForIncomingMsg(incomingMsgReceiver receiverFunction) {
        listeners.push_back(receiverFunction);
    }

    void CommonIO::incomingMsgReceived(char* buf) {
        for (unsigned int j = 0; j < listeners.size(); j++) {
                listeners[i](buf);  //error, segmentation fault..how do i call it?
            }
    }

Main.h

class Main {
public:
     static void msgReceived(char*);
     void mainLoop();

}

Main.cpp的

void Main::msgReceived(char* msg)
{
    printf("\n\n --------->>>>> %s \n\n" , msg);
}

void Main::mainLoop()
{
     CommonIO::incomingMsgReceiver receiver = &Main::msgReceived;
     CommonIO::getInstance()->registerForIncomingMsg( receiver );
}

incomingMsgReceived函数由异步进程调用

该程序编译得很好..但是在:listenersi;线。 这个的正确语法是什么?

1 个答案:

答案 0 :(得分:2)

为什么不使用继承和公共基类?使代码更简单,您也可以使用对象进行详细设计,以便获得数据,其他方法等。

即。像这样的东西

class incomingMsgReceiver {
   public:
      virtual void msgReceived(char *msg) = 0;
};

class MyMessage : public incomingMsgReceiver {
   public virual void msgReceieved(char *msg);
}

class OtherMyMessage : public incomingMsgReceiver {
   public virual void msgReceieved(char *msg);
}

void MyMessage::msgReceived(char *msg)
{
   /// Do stuff here

}

void msgReceived::OtherMyMessage(char *msg)
{
   /// Do stuff here

}

然后是common.h

class CommonIO
{
   private:
      std::vector<incomingMsgReceiver *> listeners;
   public:
      void addListner(incomingMsgReceiver *reveiver) { listners.push_back(reveiver); }

      void incomingMsgReceived(char*msg)
      {
         for (unsigned int j = 0; j < listeners.size(); j++)
         {
            listeners[j]->msgReceived((msg);
         }
      }
};