-1

我认为这主要是一个语法错误(虽然在编译期间没有捕获,但只有在运行时才会发生错误)

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

通用IO.h

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

通用IO.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?
            }
    }

主文件

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

}

主文件

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; 线。什么是正确的语法?

4

1 回答 1

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);
         }
      }
};
于 2013-01-01T16:40:32.003 回答