簡體   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