在C++中實(shí)現(xiàn)事件機(jī)制通常需要使用回調(diào)函數(shù)或觀察者模式。下面是一種簡(jiǎn)單的實(shí)現(xiàn)方法:
#include <iostream>
#include <functional>
class Event {
public:
using Callback = std::function<void()>;
Event(Callback callback) : m_callback(callback) {}
void trigger() {
if (m_callback) {
m_callback();
}
}
private:
Callback m_callback;
};
void handleEvent() {
std::cout << "Event handled" << std::endl;
}
int main() {
Event event(handleEvent);
event.trigger();
return 0;
}
#include <iostream>
#include <vector>
class Observer {
public:
virtual void update() = 0;
};
class Subject {
public:
void addObserver(Observer* observer) {
m_observers.push_back(observer);
}
void notifyObservers() {
for (Observer* observer : m_observers) {
observer->update();
}
}
private:
std::vector<Observer*> m_observers;
};
class EventObserver : public Observer {
public:
void update() override {
std::cout << "Event handled" << std::endl;
}
};
int main() {
Subject subject;
EventObserver eventObserver;
subject.addObserver(&eventObserver);
subject.notifyObservers();
return 0;
}
以上是兩種簡(jiǎn)單的事件機(jī)制實(shí)現(xiàn)方法,實(shí)際開發(fā)中可以根據(jù)需求選擇合適的方法來實(shí)現(xiàn)事件機(jī)制。