【问题标题】:C++: Store & Call the function pointers in a vector of function pointersC++:在函数指针向量中存储和调用函数指针
【发布时间】:2020-08-21 21:34:57
【问题描述】:

我有一个如下代码的场景。我正在努力

  1. 将 C++ 成员函数的地址存储在函数指针向量中。

  2. 使用此函数指针向量访问 C++ 成员函数。

我可以添加函数,但我不能调用它们。我得到的错误是:

错误:必须使用'.'或'->'来调用指向成员函数的指针

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 
        }
}

【问题讨论】:

  • @NathanOliver:更新了用于声明函数指针向量的正确语法,但我在使用以下语法调用函数指针时遇到了问题:(我已在代码中更新。this->*fp_list .at(0)(100);
  • 我相信你需要另一组括号:this-&gt;*(fp_list.at(0))(100);
  • 实际上也试过这个,但同样的错误和“错误:必须使用'。'或 '->' 在" 中调用指向成员函数的指针
  • 啊哈,试试(this-&gt;*fp_list.at(0))(100)

标签: c++ c++11 pointers function-pointers member-function-pointers


【解决方案1】:

你需要使用

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

从向量中调用函数。当你这样做时

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

函数调用((100) 部分)绑定到 fp_list.at(0) 所以基本上你有

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

这是行不通的。在函数指针访问周围添加括号可修复 this-&gt;*fp_list.at(0) 成为要调用的函数,然后在该函数上使用 (100)

【讨论】:

    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多