gpt4 book ai didi

C++:在函数指针 vector 中存储和调用函数指针

转载 作者:行者123 更新时间:2023-12-02 10:16:48 28 4
gpt4 key购买 nike

我有一个如下代码的场景。我试图

  • 将 C++ 成员函数的地址存储在函数指针 vector 中。
  • 使用此函数指针 vector 访问 C++ 成员函数。

  • 我可以添加这些功能,但我不能调用它们。我得到的错误是:

    error: must use '.' or '->' to call pointer-to-member function in


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

    最佳答案

    你需要使用

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

    从 vector 中调用函数。当你这样做
    this->*fp_list.at(0)(100)

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

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

    关于C++:在函数指针 vector 中存储和调用函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61643390/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com