C ++ static pointer to function

I would like to have a private static function pointer in my class. Basically, it will look like this:

//file.h
class X {
private:
    static int (*staticFunc)(const X&);
    ...
public:
    void f();

};


//file.cpp
void X::f()
{
    staticFunc(*this);
}

This gives me the error "unresolved external character". I know that static members must also be initialized in .cpp, I tried this:

int (X::*staticFunc)(const X&) = NULL;

but it gives me the error of "initializing the function". This gives me a more ugly error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thank.

+3
source share
3 answers
//file.cpp  
int (*X::staticFunc)(const X&);

void X::f()  
{  
staticFunc(*this);  
}
+4
source

This is member X, so you need to say

int (*X::staticFunc)(const X&) = NULL;

staticFunc, X.

+2

.

The first error is that you are not passing a parameter when trying to use staticFunc. This should result in a compiler error that you are not reporting.

The second problem is that your syntax is incorrect. TonyK got it.

0
source

Source: https://habr.com/ru/post/1777735/


All Articles