小编Aux*_*rro的帖子

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

请考虑以下文件:

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 …
Run Code Online (Sandbox Code Playgroud)

c++ static pointers function undefined

6
推荐指数
1
解决办法
4235
查看次数

标签 统计

c++ ×1

function ×1

pointers ×1

static ×1

undefined ×1