繁体   English   中英

function 指针指向一个成员 function

[英]function pointer point to a member function

我正在研究优化算法,在我的算法中,我需要使用 function 指针将 function 传递给优化器

class 定义:

class Downhill
{
public: //
    Downhill(std::string fpath);
    ~Downhill();
    void run();
private:
    /*objfun will be passed to amoeba function by function pointer*/
    float objfun1(float *p,int ndim);
    float objfun2(float *p,int ndim);
    float objfun3(float *p,int ndim);
    void amoeba(float **p, float pval[], int ndim, float(*funk)(float *, int ndim), float ftol, int &niter);
  
private:

    float ftol;
    float TINY = 1E-10;
    int NMAX = 5000;
    std::ofstream fout;
};

在成员 function run() 的声明中,我这样做了:

float(*funk)(float *p, int dim);
funk = &(this->objfun1); // I define the function pointer here
amoeba(p, pval, ndim, funk, ftol, niter);

我有编译器错误:

error C2276:  '&': illegal operation on bound member function expression

如何在另一个成员 function 中引用成员 function? 非常感谢

获取方法指针的地址时,需要包含 class 的名称。 所以在这种情况下,适当的语法是:

&Downhill::objfun1

同时,非静态方法指针不能与常规 function 指针互换。 所以你需要将amoeba的第三个参数声明为:

float(Downhill::*funk)(float *, int ndim)

然后您需要将 function 称为this->*funk(...) 如果您需要将 object 的标识与指针捆绑在一起,那么您可以考虑将第三个参数设为std::function<float(float*, int)> (然后使用 lambda 或std::bind )。 但是,在您的情况下,这可能没有必要。

暂无
暂无

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

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