【发布时间】:2014-02-11 10:28:29
【问题描述】:
我正在尝试实现以下指向成员函数数组的指针:
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’
似乎我的调用或我的初始化与原型不匹配,但我不明白为什么。
【问题讨论】:
-
您将成员函数指针
tab[it].funcPtr应用于tab[it]对象,但它不指向tab[it]对象的成员函数。我想你想把它应用到this:(this->*(tab[it].funcPtr))(val);。 -
@jogojapan 我建议将您的评论作为答案,以便
Kernael可以接受它