在C++中監(jiān)聽(tīng)多個(gè)事件可以使用回調(diào)函數(shù)或者觀察者模式來(lái)實(shí)現(xiàn)。以下是一些技巧:
#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;
}
通過(guò)以上兩種方法,可以實(shí)現(xiàn)在C++中監(jiān)聽(tīng)多個(gè)事件的功能??梢愿鶕?jù)具體情況選擇適合的方法來(lái)實(shí)現(xiàn)。