【问题标题】:How to initialize static function pointer with non-static class function when class initing?类初始化时如何用非静态类函数初始化静态函数指针?
【发布时间】:2011-05-02 02:36:27
【问题描述】:

定义(Core.h):

static int (*foolink)(int*, char*, key*, key*);

也在 Core.cpp 中重新定义。此代码导致错误:

foolink = this->step;

错误:

Engine/Core.cpp:31: error: argument of type 'int (Core::)(int*, char*, key*, key*)' does not match 'int (*)(int*, char*, key*, key*)'

指针使用:

(*foolink)(NULL, NULL, NULL, NULL);

怎么了?请帮帮我!

【问题讨论】:

    标签: c++ class function-pointers


    【解决方案1】:

    在 C++ 程序中,大多数函数是成员函数;也就是说,它们是一个类的一部分。不允许使用普通的函数指针指向成员函数;相反,您必须使用成员函数指针。

    在您的情况下,您可以将其定义为

         v you have to name the class here
    int (YourClass::*foolink)(int*, char*, key*, key*);
    foolink = &YourClass::step;
    
    // This is how you can call the function via member function pointer
    YourClass object, *pObject = &object;
    // One way is to envoke the function from object
    (object.*foolink)(...);
    // The other way is from pointer to object
    (pObject->*foolink)(...);
    

    C++ 常见问题解答:

    Pointers to Member Functions

    【讨论】:

    • 怎么称呼它? (Core::*foolink)(NULL, NULL, NULL, NULL) 不起作用!
    • @HiTECNOLOGYs:我将更新我的答案以涉及函数的调用:)
    【解决方案2】:

    this->step 的类型必须是返回整数并以 int*、char*、key* 和 key* 作为参数的函数。显然不是。请记住,将类方法分配给普通函数是行不通的;它们都必须是方法,或者都是普通功能,但不能混合使用,这就是我怀疑您正在尝试做的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 2020-04-14
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多