2014-02-11 83 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);