1

我已经问过我的问题,现在我在下一步。在下面的代码中,我遇到了问题,我总是必须使 EventHandler (Server::HandleMessage) 静态。但是我需要让它非静态才能从处理程序中访问服务器类中的其他变量。

我怎样才能做到这一点?

这是我的代码:

#include <iostream>
#include <functional>

using namespace std;

class Client{
    public:
        struct MessageReceiveArgs {
            MessageReceiveArgs(int ID, const std::string& Text) : ID(ID), Text(Text) {}
            int ID;
            std::string Text;
        };

        std::function<void(MessageReceiveArgs)> onMessageReceive;
        Client(){}

        void FireEvent(){
            this->onMessageReceive(MessageReceiveArgs(16, "SomeText"));
        }
};

class Server{
    public:
        int i;

        Server(){
            this->client.onMessageReceive = &Server::HandleMessage;
            this->i = 5;
        }

        void FireEvent(){
            this->client.FireEvent();
        }

        Client client;

        static void HandleMessage(Client::MessageReceiveArgs args) {
            std::cout<<"ID "<<args.ID<<": "<<" "<<args.Text<<std::endl;

            //need it non static
            //std::cout<<"I: "<<this->i<<std::endl;
        }
};

int main() {
    Server sv = Server();
    sv.FireEvent();
}

正如我之前的帖子中提到的,我是标准 C++ (Unix) 的新手。

4

1 回答 1

2

我很确定这就是你所追求的。在以您似乎想要的方式this调用指向成员的指针时,您需要显式地绑定隐式。std::function

#include <iostream>
#include <functional>

using namespace std;

class Client{
public:

    struct MessageReceiveArgs
    {
        MessageReceiveArgs(int ID, const std::string& Text) 
            : ID(ID), Text(Text) {}
        int ID;
        std::string Text;
    };

    Client(){}

    void FireEvent()
    {
        this->onMessageReceive(MessageReceiveArgs(16, "SomeText"));
    }

    std::function<void(MessageReceiveArgs)> onMessageReceive;
};



class Server
{
public:
    int i;

    Server()
    {
        this->client.onMessageReceive 
            = std::bind(&Server::HandleMessage, this, std::placeholders::_1);
        this->i = 5;
    }

    void FireEvent()
    {
        this->client.FireEvent();
    }

    Client client;

    void HandleMessage(Client::MessageReceiveArgs args)
    {
        std::cout<<"ID "<<args.ID<<": "<<" "<<args.Text<<std::endl;
    }
};

int main()
{
    Server sv = Server();
    sv.FireEvent();
}

输出

ID 16:  SomeText
于 2013-10-16T03:30:44.900 回答