我正在尝试实现以下指向成员函数数组的指针:
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):
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’
似乎我的调用或我的初始化与原型(prototype)不匹配,但我不明白为什么。
最佳答案
您将成员函数指针 tab[it].funcPtr
应用于 tab[it]
对象,但它不指向 的成员函数tab[it]
对象。
我想你想将它应用于this
:
(this->*(tab[it].funcPtr))(val);
关于C++ 转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21699235/