请考虑以下文件:
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)