我正在编写一个 Gameboy 模拟器,对于 CPU 的指令,我在此处使用此结构(在 cpp.hpp 中)来存储有关它们的信息。该映射用于通过等于其个人操作码的 key 来访问所有这些信息:
struct instruction {
std::string name; //name of the instruction
int cycles; //clock cycles required to be executed
int paramNum; //number of params accepted
void* function; //code to be executed
};
class Cpu {
private:
std::map<unsigned char, instruction> instrMap;
void Cpu::fillInstructions(void);
instruction addInstruction(std::string, int, int, void*);
public:
void add_A_n(unsigned char);
}
然后在 cpu.cpp 中,我有一个函数,我想将其转换为函数指针,以便将其分配给结构指令的字段。所以我有这个代码:
void Cpu::add_A_n(unsigned char n) {
//body
}
void Cpu::addInstructions(std::string name, int cycles, int paramNum, void* function) {
instruction i = {name, cycles, paramNum, function};
return i;
}
void Cpu::fillInstructions() {
instrMap[0x80] = Cpu::addInstruction("ADD A, n", 4, 0, (void*)&Cpu::add_A_n);
}
目标是从内存中获取操作码,然后使用该操作码从映射中检索有关相关指令的信息,最后通过使用 switch case 选择正确的指令来执行其功能:
((void (*)(void))instrMap[0x80].function)(); //for 0 params
((void (*)(unsigned char))instrMap[0x90].function)((unsigned char)operand); //for 1 param
我的目标是将所有函数(甚至是需要一些参数的函数)转换为结构中的函数。
各个函数正确执行,但引发警告:
警告:从“void (Cpu::)()”转换为“void”[-Wpmf-conversions] instrMap[0x80] = Cpu::addInstruction("ADD A, n", 4, 0, (void*)&Cpu::add_A_n);
如何解决这个问题以及为什么会出现这个问题?谢谢
最佳答案
&Cpu::add_A_n
返回 pointer to a member function ,这与普通的函数指针有很大不同,两者不能混用。指向成员函数的指针的怪异之处在于,非静态成员函数都需要 this
实例才能调用该函数。
就您而言,如果像 add_A_n
这样的函数确实不依赖于 this
,只需将其设置为 static
即可,或者将其设置为非静态成员函数:
class Cpu {
...
static add_A_n(unsigned char);
};
这样就不再需要调用this
,&Cpu::add_A_n
就变成了普通的函数指针。
关于c++ - 如何将函数赋值给函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55307052/