繁体   English   中英

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

[英]How to properly pass member function as a parameter

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

我的代码:

#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();
}

结果:

错误:无法使用类型为'int(Test :: )(int,int)' 的右值初始化'Test :: funcPtr'类型的参数(aka'int( )(int,int)')

预期结果:

8
2

您的方法应该是“常规”函数。 给它们添加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;
    }
};

您应该阅读有关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);

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

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

该解决方案将产生正确的结果,而无需使用指针的复杂性。

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

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

#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();
}

暂无
暂无

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

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