c++ - 如何将 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());
}
解决方案
// 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);
推荐阅读
- python - 如何在脚本中设置代理并在 python 中使用 mqtt-paho 发布主题?
- mongodb - 如何在 groovy 中使用 objectID 访问任何列?
- android - 应用程序构建问题,从过去 45 分钟开始运行
- dask - 使用多列作为索引旋转 dask 数据帧
- laravel - 如何使配置文件用户禁止除自己用户之外的任何人?
- mongodb - 如何将 mongodb 数据从 docker 容器挂载到 Windows 10 上的 localhost 存储?
- java - java - 如何在java中的两个椭圆曲线点上使用XOR运算符?
- c++ - 只要引用不超过对象,存储对(可能)临时对象的引用是否合法?
- c# - Xamarin Forms iOS CustomRenderer Entry PlaceHolder 和 Button Text Padding Bottom
- .net - 使用 Jenkins 构建时,Xamarin.Forms 项目中缺少 netstandard 2.0 参考