在C ++类中映射函数

时间:2014-04-15 08:28:44

标签: c++ map member member-function-pointers

好的,所以我试图在.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;
    ^

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

#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
};

任何帮助或建议将不胜感激。感谢

3 个答案:

答案 0 :(得分:1)

在C ++类声明中,你不能拥有成员初始化或可执行语句,有这个

functions["load"] = load;

在构造函数

答案 1 :(得分:1)

只能在类中初始化静态const积分数据成员。您可能需要将functions["load"] = load;移动到函数的定义中。

而且,您需要将它们更改为:

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

答案 2 :(得分:0)

看看你的班级声明:除了

之外,所有的编译都很好
functions["load"] = load;

这是一个赋值,并用某些东西初始化函数映射。在声明中允许,这是一个“合同”(在接口的情况下)或“解释”你的类是如何组成的以及有哪些方法/成员。

进行此类初始化的正确位置在构造函数的定义中(即在代码中实际包含方法代码的部分,特别是当您打算创建对象时)初始化东西..即构造函数)。