将指针类方法作为参数传递给其他类方法C
Passing a pointer class method as an argument to another class method C++
我已经阅读了许多有关将指针传递给类方法的指针到其他类方法的文章,但是找不到明确的答案/理解我应该如何解决我的特定问题。
我看过的一些:
将指针传递到类成员函数作为参数
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);
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 将指针类方法作为参数传递给其他类方法C
- 我应该删除来自其他函数或类方法的指针吗?
- 如果派生类包含其他方法和成员,则可以static_cast从基类到派生类
- 在其他方法之前运行的C 类方法
- 如何在 c++ 中使用虚拟类从其他类调用方法
- 内联类方法,用于调用其他文件的 anon 命名空间中的函数
- 视觉提升 条件变量中的同步队列C++不通知其他线程上的等待类方法
- 抽象类方法用其他基类的子类实现
- 在其他类方法中使用构造函数中的object
- Std::remove_if使用其他类方法
- c++在类之间传递指针-访问其他类方法
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?