简体   繁体   English

C ++静态指向函数的指针

[英]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: 我知道静态成员也必须在.cpp中初始化,我试过这个:

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. 如果没有“= NULL”,我会得到同样的错误。

Thanks. 谢谢。

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

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

It's a member of X, so you need to say 它是X的成员,所以你需要说

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. 否则,您只需创建一个名为staticFunc的全局变量,该变量与X的静态成员无关。

Couple problems here. 这里有几个问题。

First error is that you're not passing a parameter in your attempt to use staticFunc. 第一个错误是您在尝试使用staticFunc时没有传递参数。 This should cause a compiler error that you're not reporting. 这应该导致您没有报告的编译器错误。

Second issue is that your syntax is wrong. 第二个问题是您的语法错误。 TonyK got that one. TonyK得到那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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