将函数保存在数组C++中

Save functions in Arrays C++

本文关键字:C++ 数组 存在 函数 保存      更新时间:2023-10-16

我有一个新问题,我正在使用一个名为解释器的类:

口译员.h

#ifndef INTERPRETER_H_
#define INTERPRETER_H_
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
class Interpreter {
public:
   static Interpreter* getInstance();
   typedef void (*fn)(int, int, int, int);
   static fn opcodes[44];
   static fn functions[43];
private:
   Interpreter() {
      opcodes[9] = addiu;
      opcodes[3] = jal;
      opcodes[8] = addi;
      opcodes[4] = beq;
      opcodes[43] = sw;
      functions[32] = add;
      functions[33] = addu;
      functions[34] = sub;
      functions[18] = mflo;
      functions[26] = div;
      functions[12] = syscall;
      functions[8] = jr;
}
;
void addiu(int, int, int, int);
void addi(int, int, int, int);
void jal(int, int, int, int);
void beq(int, int, int, int);
void sw(int, int, int, int);
void add(int, int, int, int);
void addu(int, int, int, int);
void sub(int, int, int, int);
void mflo(int, int, int, int);
void div(int, int, int, int);
void syscall(int, int, int, int);
void jr(int, int, int, int);

static Interpreter* _instance;
};
 #endif /* INTERPRETER_H_ */

解释器.cpp

#include "Interpreter.h"
Interpreter* Interpreter::_instance = NULL;
Interpreter* Interpreter::getInstance() {
if (_instance == NULL) {
    _instance = new Interpreter();
}
return _instance;
}

 void Interpreter::addiu(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::addi(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::jal(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::beq(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::sw(int rs, int rt, int rd, int shamt) {
 }

 void Interpreter::add(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::addu(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::sub(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::mflo(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::div(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::syscall(int rs, int rt, int rd, int shamt) {
 }
 void Interpreter::jr(int rs, int rt, int rd, int shamt) {
 }

但是当我试图将函数保存在数组操作码或函数中时,程序在.h文件中有错误,正是在私有构造函数解释器()中。

错误为:

无法将"Interpreter::addu"从类型"void(Interpreter::)(int,int,int)"转换为类型"Interpreter::fn{aka void(*)(int、int、int)}"

谢谢你的帮助我

不能用普通函数指针指向非静态成员函数。您需要使用成员函数指针:

typedef void (Interpreter::*fn)(int, int, int, int);