【问题标题】:Pointer to member function of an object [duplicate]指向对象成员函数的指针[重复]
【发布时间】:2017-06-29 21:35:16
【问题描述】:

我想将一个函数与 gsl 集成。因此,我必须定义一个函数f(集成者,其格式必须为double (*)(double, void*))。对于 gsl 集成方法的调用,我需要定义一个结构,它包含一个指向函数的指针(这个结构称为gsl_function)。

gsl_function F;
F.function = &MyClass::my_f;

函数f 必须在一个类中实现(在应该调用集成过程的同一个类中)。我怎样才能正确分配上面的指针,因为第二行没有编译并导致错误:

cannot convert ‘double (MyClass::*)(double, void*)’ to ‘double (*)(double, void*)’ in assignment.

这里是my_f的定义

 struct my_f_params { double a; double b;};

   double my_f (double x, void * p) {
   struct my_f_params * params = (struct my_f_params *)p;
   double a = (params->a);
   double b = (params->b);
   return 1.0/(sqrt(a * (1.0 + x)*(1.0 + x)*(1.0 + x) + (1-a) * std::pow((1.0 + x), (3.0 * (1.0 + b))))); 
    }

【问题讨论】:

  • 您需要提供一个static 成员函数作为回调。我想void* 参数可以(错误)用于根据需要传递您的this 指针。
  • 指向成员的指针不是普通的指针。您必须将其包装在一个平面函数中。 SO上有很多这种技术的例子。
  • 想想gsl_function::functionvoid*参数。它可能用于什么?

标签: c++ pointers gsl


【解决方案1】:

格式必须为double (*)(double, void*)

非静态成员函数声明涉及错误消息中所述的隐式调用范围限定符

double (MyClass::*)(double, void*)
     // ^^^^^^^^^

这与回调函数指针定义不同。

你可以用这样的接口做的,是通过回调函数的void*参数传递this指针:

class MyClass {
    static double func(double d,void* thisPtr) {
        MyClass* myClass = (MyClass*)thisPtr;
        // do something
    }
};

in the documentation 所述,您可以在包装类中设置类似的参数:

class gsl_function_wrapper {
public:    
    gsl_function_wrapper() {
         F.function = &func;
         F.params = this;
    }
private:
    gsl_function F;

    double a;
    double b;

    static double func(double d,void* thisPtr) {
        gsl_function_wrapper* myWrapper = (gsl_function_wrapper*)thisPtr;
        // do something with a and b
        foo(d,myWrapper->a,myWrapper->b);
    }
};

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
相关资源
最近更新 更多