在C++中监听多个事件可以使用回调函数或者观察者模式来实现。以下是一些技巧:
#include <iostream>
#include <functional>
class EventListener {
public:
void registerCallback(std::function<void()> callback) {
callbacks.push_back(callback);
}
void fireEvent() {
for (auto& callback : callbacks) {
callback();
}
}
private:
std::vector<std::function<void()>> callbacks;
};
int main() {
EventListener listener;
listener.registerCallback([]() {
std::cout << "Event 1 occurred" << std::endl;
});
listener.registerCallback([]() {
std::cout << "Event 2 occurred" << std::endl;
});
listener.fireEvent();
return 0;
}
#include <iostream>
#include <vector>
class Observer {
public:
virtual void onEvent() = 0;
};
class Subject {
public:
void addObserver(Observer* observer) {
observers.push_back(observer);
}
void fireEvent() {
for (auto& observer : observers) {
observer->onEvent();
}
}
private:
std::vector<Observer*> observers;
};
class Event1Observer : public Observer {
public:
void onEvent() override {
std::cout << "Event 1 occurred" << std::endl;
}
};
class Event2Observer : public Observer {
public:
void onEvent() override {
std::cout << "Event 2 occurred" << std::endl;
}
};
int main() {
Subject subject;
Event1Observer event1Observer;
Event2Observer event2Observer;
subject.addObserver(&event1Observer);
subject.addObserver(&event2Observer);
subject.fireEvent();
return 0;
}
通过以上两种方法,可以实现在C++中监听多个事件的功能。可以根据具体情况选择适合的方法来实现。