在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;
}
以上是兩種簡單的事件機制實現方法,實際開發中可以根據需求選擇合適的方法來實現事件機制。