[英]How Should I Define an Array of Pointers to Functions in C++?
I'm trying to make an array of functions so I can call functions from the array with an index.我正在尝试制作一个函数数组,以便我可以使用索引调用数组中的函数。 I can't seem to figure out the parentheses, asterisks and brackets to create this array of functions.
我似乎无法弄清楚括号、星号和括号来创建这个函数数组。 Here is what I have:
这是我所拥有的:
void Game::getPawnMoves(int position, bool color, Move ** moveList) {
...
}
typedef void (*GetMoveFunction) (int, bool, Move **);
void Game::getLegalMoves(Move ** moveList) {
GetMoveFunction functions[] =
{
getPawnMoves,
getKnightMoves,
getBishopMoves,
getRookMoves,
getQueenMoves,
getKingMoves
};
...
}
All of the getPawnMoves, getKnightMoves, and the rest all have the same arguments and all return void.所有 getPawnMoves、getKnightMoves 和 rest 都具有相同的 arguments 并且全部返回无效。 Move is just a struct with two chars and an enum.
Move 只是一个包含两个字符和一个枚举的结构。 In this case, if you'd like to try compiling it, you could replace Move ** with int **.
在这种情况下,如果您想尝试编译它,可以将 Move ** 替换为 int **。
The error I'm getting when I compile is:我编译时遇到的错误是:
Game.cpp:443:5: error: cannot convert ‘Game::getPawnMoves’ from type
‘void (Game::)(int, bool, Move**) {aka void (Game::)(int, bool, Move_t**)}’ to
type ‘GetMoveFunction {aka void (*)(int, bool, Move_t**)}’
So for some reason the compiler thinks that GetMoveFunction is void * instead of void, but if I change the typedef to所以出于某种原因,编译器认为 GetMoveFunction 是 void * 而不是 void,但是如果我将 typedef 更改为
typedef void (GetMoveFunction) (int, bool, Move **);
I get the error:我收到错误:
Game.cpp:435:28: error: declaration of ‘functions’ as array of functions
GetMoveFunction functions[] =
I'm honestly super stuck on this one.老实说,我超级坚持这个。 Thanks so much for your help!
非常感谢你的帮助!
How Should I Define an Array of Pointers to Functions in C++?
我应该如何在 C++ 中定义一个函数指针数组?
typedef void (*GetMoveFunction) (int, bool, Move **);
This is a pointer to function.这是指向 function 的指针。
GetMoveFunction functions[] = { //... };
This is an array of pointers to functions.这是指向函数的指针数组。 You've achieved what you asked for in the title of the question.
您已经实现了问题标题中的要求。
Game.cpp:443:5: error: cannot convert 'Game::getPawnMoves' from type 'void (Game::)(int, bool, Move**) {aka void (Game::)(int, bool, Move_t**)}' to type 'GetMoveFunction {aka void (*)(int, bool, Move_t**)}'
The problem here is that you are trying to initialise the function pointers using non-static member functions.这里的问题是您正在尝试使用非静态成员函数初始化 function 指针。 Function pointers cannot point to non-static member functions.
Function 指针不能指向非静态成员函数。
What you probably need is an array of pointers to member functions of Game
instead.您可能需要的是一个指向
Game
成员函数的指针数组。 Another option is an array of type erasing function wrappers ( std::function
).另一种选择是类型擦除 function 包装器 (
std::function
) 的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.