我的目标是编写一个系统来处理游戏事件,这些事件可以由发生的某种事件触发,例如玩家走路杀死东西或得到物品或你有什么。为此,我需要有一个在事件触发时执行的虚函数。这是我想做的事情的要点(我知道它在当前状态下不起作用,但这是我可以解释我的目标的最佳方式):
class EventManager
{
public:
typedef struct
{
virtual void run();
bool triggered;
std::string name;
} Event;
void newEvent(std::string eventName)
{
Event newEvent;
newEvent.name = eventName;
newEvent.triggered = false;
eventStack.push_back(newEvent);
}
void triggerEvent(std::string eventName)
{
std::vector<Event>::iterator itr;
for(itr = eventStack.begin(); itr != eventStack.end(); itr++)
{
if(itr->name == eventName) itr->triggered = true;
}
}
std::vector<Event> eventStack;
};
int main()
{
EventManager* myEventManager = 0;
myEventManager = new EventManager();
myEventManager->newEvent("Event1");
myEventManager->eventStack.back()::run()
{
std::cout << "Event1 has been triggered";
}
std::vector<EventManager::Event>::iterator itr;
for(itr = myEventManager->eventStack.begin(); itr != myEventManager->eventStack.end(); itr++)
{
if(itr->triggered)
{
itr->run();
itr->triggered = false;
}
}
return 0;
}
所以基本上我的问题是,我怎样才能允许我的库的用户定义触发事件时会发生什么,而不必让他们为每个事件编写一个类或其他东西?