gpt4 book ai didi

c++ - 如何将void函数传递给另一个void函数?

转载 作者:行者123 更新时间:2023-12-01 14:40:00 24 4
gpt4 key购买 nike

我有一个文字冒险游戏,当您进入一个房间时,它将显示一些文字,然后转到下一个房间。每个房间都是一个功能。我想做一个功能,使我可以设置原始房间要进入的下一个房间(或功能),因为这样可以节省很多时间。我知道下面的代码不起作用,但是有没有办法将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());
}

最佳答案

// 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);

关于c++ - 如何将void函数传递给另一个void函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59657642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com