C++ 转换错误

标签 c++ class pointers member

我正在尝试实现以下指向成员函数数组的指针:

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/

相关文章:

class - 是否可以在 typescript 中创建动态 getter/setter?

c++ - 在类中调用类

c - realloc 将对旧指针做什么

c++ - 初始化列表中的非常量表达式无法从类型 'unsigned long' 缩小到 'int'

c++ - 仅专门化模板类的一部分,同时保持其余部分通用

c++ - 在 Boost 文件系统中使用环境变量

c++ - 在构造函数中设置 C++ 类 char*

C++ : calling an Abstract method inside an abstract class

java - 从其他类调用代码

c++ - 通过参数给指针赋值