请考虑以下文件:
p.h:
#ifndef _p_h_
#define _p_h_
class p{
public:
static void set_func(int(*)());
private:
static int (*sf)();
};
#endif
p.cpp:
#include "p.h"
#include <cstdio>
int (p::*sf)() = NULL; //defining the function pointer
void p::set_func(int(*f)()){
sf = f;
}
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);
}
编译时,我明白了:
$ 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
但:
$ g++ -c -o pp p.cpp
编译正确。
代码有什么问题?我只是找不到问题所在,请你的帮助不仅仅是感谢。
感谢。
答案 0 :(得分:12)
您定义p::sf
的尝试不正确 - 您的定义是名为sf
的全局变量int (p::*)()
的定义,即指向成员函数的指针。因此p::sf
仍未定义,因此链接器错误。
请改为尝试:
int (*p::sf)() = 0;
// or,
typedef int (*p_sf_t)();
p_sf_t p::sf = 0;
答案 1 :(得分:4)
不同之处在于,只有在实际链接程序时才会出现错误。问题在于声明静态函数指针。正确的语法是:
int (*p::sf)() = NULL; //defining the function pointer
答案 2 :(得分:3)
您定义成员函数指针而不是函数指针。我不确定正确的语法是什么,但我会尝试这样的事情:
int (*p::sf)() = NULL;
答案 3 :(得分:1)
我不会给出另一个答案(ildjarn答案是正确的)但我会建议你在没有静态初始化的情况下实现相同的另一种方式(以及它所暗示的负担)
class p{
public:
typedef int (*func_t)();
static void set_func(func_t v) {
func_t& f = getFuncRef();
f = v;
}
static void call_func() {
func_t& f = getFuncRef();
assert( f != 0);
f();
}
private:
static func_t& getFuncRef() {
static func_t sf = 0;
return sf;
}
};
以这种方式将静态初始化委托给静态函数变量,该变量没有影响静态数据变量的初始化顺序问题,并且是惰性初始化的