首页 > 解决方案 > 如何将 void 函数传递给另一个 void 函数?

问题描述

我有一个文字冒险游戏,当你进入一个房间时,它会显示一些文字,然后去下一个房间。每个房间都是一个功能。我想做一个功能,让我可以设置原来房间去的下一个房间(或功能),因为这会节省我很多时间。我知道下面的代码不起作用,但是有没有办法将void类型函数作为另一个void类型函数的参数传递?(如下图)

#include <iostream>
using namespace std;

void room2();
void room1();
void room(void a);

void room1()
{
    cout << "next room" << endl;
}

void room2()
{
    cout << "other rooom" << endl;
}

void room(void a)
{
    cout << "Things happen here now you go to the next room" << endl;
    a();
}

int main()
{
    room(nextRoom());
}

标签: c++windows

解决方案


// declare a type of function pointer
typedef void (*room_ptr)();

// declare a method that takes a function pointer as arg
void room(room_ptr a)
{
    // call the function passed in... 
    a();
}

// store the current room 
room_ptr current_room = room1;

// easy to modify later
current_room = room2;

// and just call... 
room(current_room);

推荐阅读