如何正确地将成员函数作为参数传递

时间:2019-07-13 14:45:51

标签: c++

如何正确地将成员函数作为参数传递?

MyCode:

#include <iostream>

using namespace std;

class Test
{
public:
    int add(int a, int b)
    {
        return a + b;
    }
    int sub(int a, int b)
    {
        return a - b;
    }
    typedef int (*funcPtr)(int a, int b);
    int myFunc(funcPtr func, int a, int b)
    {
        return func(a, b);
    }
    void setup()
    {
        cout << myFunc(&Test::add, 5, 3) << endl;
        cout << myFunc(&Test::sub, 5, 3) << endl;
    }
};

int main()
{
    Test test;
    test.setup();
}

结果:

  

错误:无法初始化'Test :: funcPtr'类型的参数(又名'int   ()(int,int)'),其右值类型为'int(Test :: )(int,int)'

预期结果:

8
2

3 个答案:

答案 0 :(得分:3)

您的方法应该是“常规”功能。将static添加到它们中,以允许它们与函数指针一起使用:

class Test
{
public:
    static int add(int a, int b)
    {
        return a + b;
    }
    static int sub(int a, int b)
    {
        return a - b;
    }
// ...
};

如果您确实指向方法,则应将int (*funcPtr)(int a, int b)替换为int (Test::*funcPtr)(int a, int b),并使用类似的方法:

class Test
{
public:
    int add(int a, int b)
    {
        return a + b;
    }
    int sub(int a, int b)
    {
        return a - b;
    }
    typedef int (Test::*funcPtr)(int a, int b);
    int myFunc(funcPtr func, int a, int b)
    {
        return (this->*func)(a, b);
    }
    void setup()
    {
        cout << myFunc(&Test::add, 5, 3) << endl;
        cout << myFunc(&Test::sub, 5, 3) << endl;
    }
};

答案 1 :(得分:1)

您应该阅读有关std:: functionstd::bind的信息。第一件事将允许您存储具有多种形式的函数指针(Functor,lamda,bind),第二件事将使您可以将参数绑定到函数调用(在您的情况下,您想绑定该类的实例)需要调用您的函数)。

std:: function<int(int, int)> func = std::bind(&Class::Method, instancePtr, std::placeholders::_1, std:: placeholders::_2);
int result = func(a, b);

但是,在您的上下文中,应将您的方法标记为静态(它们未使用类的任何非静态成员),但是我提供的示例和解释将回答您的基本问题

答案 2 :(得分:0)

首先,根据您的问题,最好的解决方案是不使用指针,而是将您的方法声明为静态方法,并按如下所示直接调用它们。

该解决方案将在不使用指针的复杂性的情况下产生正确的结果。

如果您不需要使用指针,简单会更好,最好不要使用它们。代码也将更具可读性。

以下代码有效,我对其进行了测试:

#include <iostream>

using namespace std;



class Test
{
public:
  static  int add(int a, int b)
    {
        return a + b;
    }
   static int sub(int a, int b)
    {
        return a - b;
    }


    void setup()
    {
        cout << add( 5, 3) << endl;
        cout << sub(5, 3) << endl;
    }

};

int main()
{
    Test test;
    test.setup();
}
相关问题