函数指针问题:如何提供从非成员函数到成员函数的指针

Function pointer issue: How to provide pointer from non member function to member function

我需要做这样的事情...,在我的一个项目中。

class Alpha{
    
public:
    Alpha(void* p(int, int) = nullptr);
        
    void* calculatePointer;
    
    void test();
};
    

Alpha::Alpha(void* p(int, int)) : calculatePointer(p){};

Alpha::test(){
        calculatePointer(5, 10);
    }  


  
    
void calculate(int a, int b){
    std::cout << "cum: " << a +b << "\n";  
}
    
    
int main(){
    
    Alpha A = Alpha(&calculate);
    A.test();
    
}

它会导致这些错误:

error: invalid conversion from ‘void* (*)(int, int)’ to ‘void*’ [-fpermissive]
       15 |     : calculatePointer(p),
          |                        ^
          |                        |
          |                        void* (*)(int, int)
error: cannot initialize a member subobject of type 'void *' with an lvalue of type 'void *(*)(int, int)'
     error: expression cannot be used as a function
     In constructor 'Alpha::Alpha(void* (*)(int, int))':
    error: invalid conversion from 'void (*)(int, int)' to 'void* (*)(int, int)' [-fpermissive]
note: initializing argument 1 of 'Alpha::Alpha(void* (*)(int, int))'

这只是一个假人,但这就是我要做的。
如何正确完成?

如果您对函数指针的确切语法感到困惑,最好定义一个类型别名。

如果您使用 using,则“rhs”为 <return type> (*)(<parameter types>)

class Alpha{
    
public:
    using FunctionPtr = void (*)(int, int);

    Alpha(FunctionPtr p = nullptr) : calculatePointer(p) {}
        
    FunctionPtr calculatePointer;
    
    void test()
    {
        if (calculatePointer != nullptr)
        {
            calculatePointer(5, 10);
        }
    }
};
    
void calculate(int a, int b){
    std::cout << "sum: " << (a + b) << "\n";  
}

顺便说一句:没有类型别名的正确语法是

Alpha(void (*p)(int, int) = nullptr);

括号是必需的,因为编译器将 void *p(int, int) 视为 (void*) p(int, int)