在C++中实现事件机制通常需要使用回调函数或观察者模式。下面是一种简单的实现方法:
#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;
}
以上是两种简单的事件机制实现方法,实际开发中可以根据需求选择合适的方法来实现事件机制。