gpt4 book ai didi

C++ 事件处理 - const 问题

转载 作者:行者123 更新时间:2023-11-30 04:13:32 25 4
gpt4 key购买 nike

我已经问过我的问题,现在我正在进行下一步。在下面的代码中,我遇到了问题,我总是必须将 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) 的新手。

最佳答案

我很确定这就是您想要的。当以您似乎想要的方式通过 std::function 调用指向成员的指针时,您需要显式绑定(bind)隐式 this

#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

关于C++ 事件处理 - const 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com