在c ++中回调成员函数

class scanner { private: string mRootFilePath; static int AddToIndex( const char *,const struct stat *,int); public: scanner(string aRootFilePath){ mRootFilePath = aRootFilePath; } string GetFilepath(){ return mRootFilePath; } void Start(); }; int scanner :: AddToIndex(const char *fpath, const struct stat *sb,int typeflag) { fprintf(stderr,"\n%s\t%d",fpath,typeflag); return 0; } void scanner :: Start() { ftw(mRootFilePath.c_str,(int (*)( const char *,const struct stat *,int))scanner :: AddToIndex,200); } main() { int i; scanner test("."); test.Start(); } 

当我编译此代码时,我收到错误消息

  main.c: In member function 'void scanner::Start()': main.c:34: error: argument of type 'const char* (std::basic_string<char, std::char_traits, std::allocator >::)()const' does not match 'const char*' 

ftw函数在这种情况下调用回调函数AddToIndex()函数,它是类“scanner”的成员函数..如何使这个成员函数AddToIndex作为回调函数? 以及如何解决这个问题……

在您对ftw的调用中,第一个参数是mRootFilePath.c_str 。 也许你想要mRootFilePath.c_str()

除了Managu的答案之外,不要忘记确保您的static成员函数使用C链接( extern "C" ) – 根据实现,您可能无法将指针传递给具有默认C ++链接的函数预期指向C函数的指针(当ABI不同时)。