简体   繁体   English

C++:在 function 指针向量中存储和调用 function 指针

[英]C++: Store & Call the function pointers in a vector of function pointers

I've a scenario as below code.我有一个如下代码的场景。 I'm trying to我试着

  1. Store the address of a C++ member function in a vector of function pointers.将 C++ 成员 function 的地址存储在 function 指针向量中。

  2. access a C++ member function using this vector of function pointers.使用 function 指针向量访问 C++ 成员 function。

I am able to add the functions, but I can't call them.我可以添加这些功能,但我不能调用它们。 The error I get is:我得到的错误是:

error: must use '.错误:必须使用'. ' or '-> ' to call pointer-to-member function in ' 或 '-> ' 调用指向成员 function 的指针

class allFuncs {
     private:
        std::vector<void *(allFuncs::*)(int)> fp_list; // Vector of function pointers

       void func_1(int a) {
           // some code
        }

       void func_2(int a) {
           // some code
        }

        void func_3() {
           // STORING THE FUNCTION POINTER INTO The VECTOR OF FUNCTION POINTERS
           fp_list.push_back(&func_2);
           fp_list.push_back(allFuncs::func_1);      
        }

        func_4() {
          // Calling the function through the function pointer in vector
          this->*fp_list.at(0)(100);  // this does not work 
        }
}

You need to use你需要使用

(this->*fp_list.at(0))(100)

to call the function from the vector.从向量中调用 function。 When you do当你这样做

this->*fp_list.at(0)(100)

The function call (the (100) part) is bound to fp_list.at(0) so basically you have function 调用( (100)部分)绑定到fp_list.at(0)所以基本上你有

this->*(fp_list.at(0)(100))

which won't work.这是行不通的。 Adding parentheses around the function pointer access fixes that so this->*fp_list.at(0) becomes the function to call and then the (100) is used on that function.在 function 指针访问周围添加括号可修复此问题,因此this->*fp_list.at(0)变为 function 以调用,然后(100)用于该 ZC1C425268E68385D1AB470。

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

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