c ++中对静态函数指针成员的未定义引用,我做错了什么?

Aux*_*rro 6 c++ static pointers function undefined

请考虑以下文件:

PH值:

#ifndef _p_h_
#define _p_h_

class p{
public:    
    static void set_func(int(*)());

private:
    static int (*sf)();

};
#endif
Run Code Online (Sandbox Code Playgroud)

p.cpp:

#include "p.h"
#include <cstdio>

int (p::*sf)() = NULL;    //defining the function pointer

void p::set_func(int(*f)()){
    sf = f;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

#include "p.h"
#include <iostream>

int function_x(){
        std::cout << "I'm function_x()" << std::endl;
        return 1234;
}

int main(){
        p::set_func(function_x);
}
Run Code Online (Sandbox Code Playgroud)

在编译时,我得到这个:

$ g++ -o pp main.cpp p.cpp
/tmp/ccIs0M7r.o:p.cpp:(.text+0x7): undefined reference to `p::sf'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

但:

$ g++ -c -o pp p.cpp
Run Code Online (Sandbox Code Playgroud)

编译正确.

代码有什么问题?我只是找不到问题出在哪里,请你的帮助不仅仅是赞赏.

谢谢.

ild*_*arn 12

您的定义尝试p::sf不正确 - 您的定义是名为sftype 的全局变量int (p::*)(),即指向成员函数的指针.因此p::sf仍未定义,因此链接器错误.

试试这个:

int (*p::sf)() = 0;

// or,

typedef int (*p_sf_t)();
p_sf_t p::sf = 0;
Run Code Online (Sandbox Code Playgroud)