c++ - 如何将函数赋值给函数指针?

标签 c++ c++11

我正在编写一个 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/

相关文章:

c++ - 如何将括号中的字符串解析为具有给定定界符的字符串列表

c++ - 使用 sed 命令换行字符串

c++ - 有没有 catch(...) 可以处理而 catch(exception& ex) 不能处理的异常?

c++ - OpenGL - 告诉顶点着色器 VBO 已经改变

c++ - 如何将基本代码片段/模式转换为使用 C+11 可变参数模板

c++ - 捕获自定义 UART 类信号

c++ - 一个空的别名 shared_ptr 是一个很好的替代 no-op 删除 shared_ptr 的方法吗?

c++ - std::tuple 相当于 std::pair 的第二个成员?

c++ - 尝试运行带有浮点参数的重载函数时出错。

C++ const char* 和 const char[] 的区别