2014-04-15 94 views
0

好的,我試圖映射一些我的成員函數在.h文件中,這是爲了能夠在我實現代碼時使用映射。然而,幾小時後,我無處可去,所以我想要建議,或者如果有人知道如何實現這一點。作爲參考,這些是錯誤。映射C++類函數

./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 
}; 

任何幫助或建議,將不勝感激。由於

回答

1

只有靜態常量整型數據成員可以在類中被初始化。您可能需要將functions["load"] = load;移至某個函數的定義。

而且還需要將其更改爲:

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

您還可以初始化非靜態數據成員。但是你不能有聲明,比如打電話給他們的成員。 – juanchopanza

+0

所以,你說的是,我真的可以映射我的函數之前需要構造函數頭。 – user2881196

+0

@ user2881196是的,否則編譯器找不到'功能'。 – herohuyongtao

1

在C++類的聲明,你不能有成員初始化器或可執行語句,有這一個

functions["load"] = load; 

構造函數中

0

看看你的類聲明:一切都編制精細,除了

functions["load"] = load; 

這是一個分配和初始化功能地圖一些東西。那就是而不是在聲明中被允許,聲明是一個「合約」(在接口的情況下)或「解釋」你的課程是如何組成的以及什麼方法/成員有。

正確位置把這樣的初始化是在構造函數的定義(即實際上包含你的方法的代碼的代碼的一部分,特別是當你打算初始化的東西對象被創建..即構造函數)。