c++ - C++ 类中的映射函数

标签 c++ dictionary member pointer-to-member

<分区>

好的,所以我正在尝试在 .h 文件中映射我的一些成员函数,以便在我实现代码时能够使用映射。但是,几个小时后我一无所获,所以我想提出建议,或者是否有人知道如何实现。这些是错误供引用。

./Assembler.h:51:2: error: C++ requires a type specifier for all declarations
    functions["load"] = load;
    ^~~~~~~~~
./Assembler.h:51:12: error: size of array has non-integer type 'const char [5]'
    functions["load"] = load;
              ^~~~~~
./Assembler.h:51:2: error: duplicate member 'functions'
    functions["load"] = load;
    ^

至于我的头文件,问题来自 map :

#include <vector>
#include <iostream>
#include <map>
#include <string>
#include <fstream>

using namespace std;

class Assembler {
public:

Assembler(string filename);//Argument will be passed from the os.cpp file
void parse();// Will go through the a file to output the .o file
void load();
void loadi();
void store();
void add();
void addi();
void addc();
void addci();
void sub();
void subi();
void subc();
void subci();
void ander();
void andi();
void xorer();
void xori();
void negate();
void shl();
void shla();
void shr();
void shra();
void compr();
void compri();
void getstat();
void putstat();
void jump();
void jumpl();
void jumpe();
void jumpg();
void call();
void ret();
void read();
void write();
void halt(); 
void noop();

private:
typedef void (*function)();
map<string, function> functions;
functions["load"] = load;
fstream in, out; //One will be the .s file while the other will be the .o file 
string opcode;
int rd, rs, constant, addr, machcode; //Different parts of the instruction
};

如有任何帮助或建议,我们将不胜感激。谢谢

最佳答案

在一个类中只能初始化static const 整型数据成员。您可能需要将 functions["load"] = load; 移动到函数的定义中。

此外,您需要将它们更改为:

typedef void (Assembler::*function)();
...
functions["load"] = &Assembler::load;

关于c++ - C++ 类中的映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23078325/

相关文章:

python - 我在使用 Python 2.7 字典时遇到错误

c++ - 声明一个没有长度的静态数组,然后定义一个长度是否有效?

c++ - 为什么我不应该将 "using namespace std"放在标题中?

python - 使用多个 for 和 ifs/elif 缩短循环以列表理解

c++ - 查找轮廓 OpenCV C++

python - 找到字典键的交集并将它们组合起来

c++ - 使用函数指针在类之间传递数据

function - 为什么c++11将get<>(tuple)定义为全局函数而不是tuple的成员?

c++ - 如何在 C/C++ 中从运行时卸载内存偏移量计算?

C++ 将隐式构造限制为特定值