将指针类方法作为参数传递给其他类方法C

Passing a pointer class method as an argument to another class method C++

本文关键字:类方法 其他 参数传递 指针      更新时间:2023-10-16

我已经阅读了许多有关将指针传递给类方法的指针到其他类方法的文章,但是找不到明确的答案/理解我应该如何解决我的特定问题。

我看过的一些:

将指针传递到类成员函数作为参数

c 将成员函数传递到另一个类

我真的很感谢帮助我的特定场景起作用。

我有三个类:EOM,RK4和管理。在头等舱中,我有两种方法get_pos和set_pos。

class Eom
{
    public:
        // Get methods
        double get_pos() {return pos;}
        // Set methods
        void set_pos(double pos_in) {pos = pos_in;}
    private:
        double pos;
};

在第二类中,我有一种称为Integrate的方法,我想通过eom :: get_pos和eom :: set_pos方法。

class Rk4
{
    public:
        // Method that takes a method to get_pos 
        // and a method to set_pos as input
        void integrate(Eom *p_get_func, Eom *p_set_func); 
};

管理类运行方法是我要创建指针对象的RK4和EOM,并调用RK4 Integrate方法。

class Manage
{
    public:
            // Declare pointers
            Eom *p_eom;
            Rk4 *p_rk4;
            // Run method
            void run();
};
Manage::run()
{
    p_eom = new Eom;
    p_rk4 = new Rk4;
    // Call integrate, passing in the Eom get_pos and set_pos functions;
    p_rk4->integrate(p_eom->get_pos, p_rk4->set_pos);
}

我目前会遇到以下错误:

invalid use of non-static member function
p_rk4->integrate(p_eom->get_pos, p_eom->set_pos); 

我还想以更通用的方式声明集成方法,以便我可以从其他类中传递/设置方法:

void integrate(Generic_class *p_get_func, Generic_class *p_set_func); 

感谢提前的任何帮助!

您的代码有点笨拙,我想这就是我的想法,您可以将功能封装在lambda中,并使用std ::函数像So。

传递。
#include <iostream>
#include <functional>
class Eom
{
    public:
        // Get methods
        double get_pos() {return pos;}
        // Set methods
        void set_pos(double pos_in) {pos = pos_in;}
    private:
        double pos;
};
class Rk4
{
    public:
        // Method that takes a method to get_pos 
        // and a method to set_pos as input
    void integrate(std::function<double(void)> get,std::function<void(double)> set, double val) 
    {
       int i = get();
       set(val);
    }
};

在管理课中,您可以这样使用:

class Manage
{
    public:
            // Declare pointers
            Eom *p_eom;
            Rk4 *p_rk4;
            // Run method
            void run();
};
void Manage::run()
{
    p_eom = new Eom;
    p_rk4 = new Rk4;
    double val =100;
    // Call integrate, passing in the Eom get_pos and set_pos functions;
    std::function<double(void)> a = [=]()->double { return p_eom->get_pos(); };
    std::function<void(double)> b = [=](double d)->void { return p_eom->set_pos(d); };
    p_rk4->integrate(a,b,val);
}