search

Home  >  Q&A  >  body text

C++的类中怎么使用函数指针数组呢?

我只知道这样一种,请知道的补充。
还请大牛解释一下为什么要加static

class Test
{
    private:
        typedef void(*func)(void);
        func funcPtr[2];
        

        
   public:
        Test();
        ~Test();
        static void func1(void);
        static void func2(void);
};
Test::Test()
{
    funcPtr[0] = func1;
    funcPtr[1] = func2
}
void Test::func1(void) {}
void Test::func2(void) {}
...
黄舟黄舟2803 days ago441

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:20:50

    So that's why stl has std::function. You declare a function<void(void)> instead of a function pointer, then all the function pointer types you can imagine can be put in it. If it is a class member function, you also need to bind this pointer into it, and then you can use it everywhere.

    Don’t use naked function pointers. The function pointer type of C language can only have two functions in C++:

    • To call other dlls written in C language, you have to use function pointers

    • is used to implement std::function

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:20:50

    Because the function prototype of a non-static member function (such as func1 in your Test class) is not void (*)() but void (Test::*)()
    For non-static member functions, The "0th parameter" of the function is a pointer containing a Test* type,
    like this:

     void func(Test* this, .../*some arguments*/)

    This is just a metaphor. The real function signature is not like this. The purpose is to illustrate that you cannot force a member function pointer into a non-member function
    pointer. For static member functions, this pointer is not It exists, so it can be converted.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:20:50

    #include <iostream>
    #include <stdio.h>
    using namespace std;
    
    class Test
    {
    private:
        typedef void(Test::*foo)();
        foo a[2];
    public:
        Test(){
            a[0] = &Test::func1;
            a[1] = &Test::func2;
            (this->*a[0])();
            (this->*a[1])();
        }
        void func1(){
            printf("func1 %p\n", this);
        }
        void func2(void){
            printf("func2 %p\n", this);
        }
    };
    
    int main(){
        Test t1;
        Test t2;
        return 0;
    }
    

    static represents the modification of the class. After using static, the method needs to be modified with the namespace of the class when calling the method, but the method itself is equivalent to the global method. Output
    func1 0x7ffddf3b3820
    func2 0x7ffddf3b3820
    func1 0x7ffddf3b3840
    func2 0x7ffddf3b3840
    It can be seen that the method is bound to each object, and the function decorated with static does not have this pointer.

    reply
    0
  • Cancelreply