简体   繁体   中英

C++ static pointer to function

I would like to have a private static pointer to a function in my class. Basically, it would 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 an "unresolved external symbol" error. I know that static members must be initialized in the .cpp too, I've tried this:

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

but this gives me an "initializing a function" error. It gives me an uglier error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thanks.

//file.cpp  
int (*X::staticFunc)(const X&);

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

It's a member of X, so you need to say

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

Otherwise, you'd just create a global variable called staticFunc which is not related to that static member of X.

Couple problems here.

First error is that you're not passing a parameter in your attempt to use staticFunc. This should cause a compiler error that you're not reporting.

Second issue is that your syntax is wrong. TonyK got that one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM