简体   繁体   English

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

[英]Undefined reference to static function pointer member in c++, what am I doing wrong?

please consider these files: 请考虑以下文件:

ph: PH值:

#ifndef _p_h_
#define _p_h_

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

private:
    static int (*sf)();

};
#endif

p.cpp: 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: 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);
}

when compiling, I get this: 在编译时,我得到这个:

$ 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

but: 但:

$ g++ -c -o pp p.cpp

compiles right. 编译正确。

What's wrong with the code? 代码有什么问题? I just can't find where the problem is, please your help will be more than appreciated. 我只是找不到问题出在哪里,请你的帮助不仅仅是赞赏。

Thanks. 谢谢。

Your attempt at defining p::sf is incorrect – yours is a definition of a global variable named sf that is of type int (p::*)() , ie a pointer to a member function. 你定义p::sf尝试是不正确的 - 你的是一个名为sf的全局变量的定义,它是int (p::*)() ,即指向成员函数的指针。 Consequently p::sf remains undefined, hence the linker error. 因此p::sf保持未定义,因此链接器错误。

Try this instead: 试试这个:

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

// or,

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

The difference is because error only occurs when you actually link the program. 不同之处在于,只有在实际链接程序时才会出现错误。 The problem is in your declaration of the static function pointer. 问题在于声明静态函数指针。 The correct syntax is: 正确的语法是:

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

You define a member function pointer and not a function pointer. 您定义成员函数指针而不是函数指针。 I'm not sure what the correct syntax is, but I would have tried something like this: 我不确定正确的语法是什么,但我会尝试这样的事情:

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

I will not give another answer (ildjarn answer is correct) but i will suggest you another way of achieving the same without static initialization (and the burdens it implies) 我不会给出另一个答案(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;
    }

};

in this way you delegate the static initialization to a static function variable, which doesn't have the initialization order problems that affect static data variables, and is lazy-initialised 通过这种方式,您可以将静态初始化委托给静态函数变量,该变量没有影响静态数据变量的初始化顺序问题,并且是惰性初始化的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM