这是我的课:
class Cpu
{
private:
typedef uint8_t(Cpu::*OpCode)();
OpCode *op_codes; // how to define array of 256 function pointers?
uint8_t op_nop();
uint8_t op_lxi();
uint8_t op_stax();
uint8_t op_mov();
uint8_t op_mvi();
...
};
然后我想在类构造函数中启动数组:
Cpu::Cpu()
{
op_codes = new OpCode[256] {
// 0x00
&Intel8080::op_nop,
// 0x01
&Intel8080::op_lxi,
// 0x02:
&Intel8080::op_stax,
// 0x03
...
}
最后我想使用数组:
void Cpu::SingleStep()
{
uint8_t op_code = 0x00;
*op_codes[op_code](); // how to execute the specified function?
}
任何帮助将不胜感激。谢谢!
我尝试使用各种示例来定义类中的字段。
OpCode op_codes[256];
但是如何分配 then 函数呢?
您可以使用
std::invoke
(对于 C++17)使用成员函数指针进行调用。此外,最好在成员初始化器列表中初始化数组,而不是在构造函数主体中分配给它。
//use member initializer list
Cpu::Cpu(): op_codes(new OpCode[256]{&Cpu::op_nop, &Cpu::op_lxi, &Cpu::op_stax})
{
//this is assignment
op_codes = new OpCode[256]{&Cpu::op_nop, &Cpu::op_lxi, &Cpu::op_stax};
}
void Cpu::SingleStep()
{
uint8_t op_code = 0x00;
//call using std::invoke
std::invoke(op_codes[op_code], this);
//old style call without std::invoke
(this->*op_codes[op_code])();
}