【问题标题】:Error C2065 with function pointer to static member class带有指向静态成员类的函数指针的错误 C2065
【发布时间】:2016-01-12 11:49:53
【问题描述】:

我正在尝试更改头类中静态 const 结构的现有代码,该头类用作创建数据库的基础。当前代码是

//database.h

#define VIDEODB_TYPE_INT 1
const struct DBHeaders
{
  std::string name;
  std::string dbType;
  int type;
} DBHeadersTable1[] = 
{
  { "idRow", "INTEGER PRIMARY KEY", VIDEODB_TYPE_INT},
  { "value", "INTEGER", VIDEODB_TYPE_INT}
};

const struct DBHeaders DBHeadersTable2[] = 
{
  { "idRow", "INTEGER PRIMARY KEY", VIDEODB_TYPE_INT},
  { "value", "INTEGER", VIDEODB_TYPE_INT}
};

class CDatabase
{
public:
  void getDatabaseInteger(DatabaseRow& details);
  void get(int column, DBHeaders headers, DatabaseRow& details)
  {
    if (headers[i].type == VIDEODB_TYPE_INT)
      getDatabaseInteger(details);
  }
  //other functions
}

但是这种方法不再适用了,因为现在我们有需要更改才能使用的字段。因此,我不想给出一个代表函数的数字,而是直接插入一个指向函数的指针,从而提供更大的灵活性。这是我的新代码

//database.h

typedef void (*getFunctionType)(DatabaseRow&);
const struct DBHeaders
{
  std::string name;
  std::string dbType;
  getFunctionType getFunction;
} DBHeadersTable1[] = 
{
  { "idRow", "INTEGER PRIMARY KEY", &(CDatabase::getDatabaseInteger)},
  { "value", "INTEGER", &(CDatabase::getDatabaseInteger)}
};

const struct DBHeaders DBHeadersTable2[] = 
{
  { "idRow", "INTEGER PRIMARY KEY", &(CDatabase::getDatabaseInteger)},
  { "value", "INTEGER", &(CDatabase::getDatabaseInteger)}
};

class CDatabase
{
public:
  static void getDatabaseInteger(DatabaseRow& details);

  //other functions
}

这个想法是,为我的行定义一个常量和一个指向代码必须用来解析列的函数的指针。我得到的错误是: https://msdn.microsoft.com/en-us/library/ewcf0002.aspx 在行

  { "idRow", "INTEGER PRIMARY KEY", &(CDatabase::getDatabaseInteger)},

在错误的括号之间,我没有“database.h”,而是另一个文件...... 是否可以以这种方式指向静态函数?我做错了吗?

【问题讨论】:

  • 函数类型需要声明一个成员函数类型才能使其工作:typedef void (CDatabase::*getFunctionType)(DatabaseRow&);。另请注意,您没有将此函数声明为 static 成员。
  • 好点..我使用了成员函数类型,但我仍然得到那个错误。
  • 您不需要为静态类方法声明成员函数类型。
  • 上面给定的 typedef 是错误的,指向静态方法的指针不应该包含类名 - 这是不必要的。我相信错误是由在赋值中使用未声明的函数引起的。

标签: c++ function pointers static


【解决方案1】:

根据您发布的代码,在我看来您需要声明该类:

class CDatabase
{
public:
  static void getDatabaseInteger(DatabaseRow& details);

  //other functions
};

同一个头文件中所有引用CDatabase::getDatabaseInteger()方法的数组之前。看起来在您的头文件中,您在实际声明它之前引用了静态函数。将此声明移动到文件的开头。

【讨论】:

  • 谢谢.. 在移动类之前而不是 const 之后它起作用了!
猜你喜欢
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多