在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++中監聽多個事件的功能。可以根據具體情況選擇適合的方法來實現。