[英]Undefined reference to static function pointer member in c++, what am I doing wrong?
请考虑以下文件:
PH值:
#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
编译正确。
代码有什么问题? 我只是找不到问题出在哪里,请你的帮助不仅仅是赞赏。
谢谢。
你定义p::sf
尝试是不正确的 - 你的是一个名为sf
的全局变量的定义,它是int (p::*)()
,即指向成员函数的指针。 因此p::sf
保持未定义,因此链接器错误。
试试这个:
int (*p::sf)() = 0;
// or,
typedef int (*p_sf_t)();
p_sf_t p::sf = 0;
不同之处在于,只有在实际链接程序时才会出现错误。 问题在于声明静态函数指针。 正确的语法是:
int (*p::sf)() = NULL; //defining the function pointer
您定义成员函数指针而不是函数指针。 我不确定正确的语法是什么,但我会尝试这样的事情:
int (*p::sf)() = NULL;
我不会给出另一个答案(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;
}
};
通过这种方式,您可以将静态初始化委托给静态函数变量,该变量没有影响静态数据变量的初始化顺序问题,并且是惰性初始化的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.