2014-02-11 82 views
1

我想實現以下成員指針數組功能:C++轉換錯誤

IOperand*  OpCreate::createOperand(eOperandType type, 
             const std::string& val) 
{ 
    size_t  it = 0; 
    OpPtrTab  tab[] = 
    { 
     {Int8, &OpCreate::createInt8}, 
     {Int16, &OpCreate::createInt16}, 
     {Int32, &OpCreate::createInt32}, 
     {Float, &OpCreate::createFloat}, 
     {Double, &OpCreate::createDouble}, 
     {Unknown, NULL} 
    }; 

    while ((tab[it]).type != Unknown) 
    { 
     if ((tab[it]).type == type) 
     return ((tab[it]).*((tab[it]).funcPtr))(val); 
     it++; 
    } 
    return NULL; 
} 

從以下類:

class OpCreate 
{ 
public : 

    struct OpPtrTab 
    { 
    const eOperandType type; 
    IOperand*   (OpCreate::*funcPtr)(const std::string&); 
    };                    

    IOperand*  createOperand(eOperandType, const std::string&); 

    OpCreate(); 
    ~OpCreate(); 

private : 

    IOperand*  createInt8(const std::string&); 
    IOperand*  createInt16(const std::string&); 
    IOperand*  createInt32(const std::string&); 
    IOperand*  createFloat(const std::string&); 
    IOperand*  createDouble(const std::string&); 
}; 

我不明白我做錯了,但這裏的編譯器錯誤:

OpCreate.cpp: In member function ‘IOperand* OpCreate::createOperand(eOperandType, const string&)’: 
OpCreate.cpp:66:39: error: pointer to member type ‘IOperand* (OpCreate::)(const string&) {aka IOperand* (OpCreate::)(const std::basic_string<char>&)}’ incompatible with object type ‘OpCreate::OpPtrTab’ 

看來,我的電話或我的初始化不符合原型,但我看不到爲什麼。

+1

您申請的成員函數指針'標籤[它] .funcPtr'到'標籤[它]'對象,但它並不指向到'tab [it]'對象的成員函數。我想你想把它應用到'this':'(this - > *(tab [it] .funcPtr))(val);'。 – jogojapan

+0

謝謝,它工作。 – Kernael

+1

@jogojapan我建議把你的評論作爲答案,以便'Kernael'可以接受它 – 2014-02-11 10:57:37

回答

1

您將成員函數指針tab[it].funcPtr應用於tab[it]對象,但它不指向tab[it]對象的成員函數。

我想你想將它應用到this

(this->*(tab[it].funcPtr))(val);