簡體   English   中英

在這種情況下,如何在C ++中正確傳遞成員函數作為參數?

[英]How to properly pass member function as argument in this situation in C++?

我想將我的C ++類的成員函數傳遞給同一類的另一個成員函數。 我做了一些研究,發現了類似的問題。

在C ++中將成員函數作為參數傳遞

指向成員函數的函數指針

他們沒有以相同的方式涵蓋我的特定案例,但是我編寫了代碼,並認為我調整了正確的部分以使其在我的情況下可以正常工作。 但是,編譯器在這方面似乎與我不同意...

我的C ++類中具有以下設置:

CutDetector.h

class CutDetector {
   double thresholdForFrameIndex(int frameIndex, vector<double> diffs, int steps, double (CutDetector::*thresholdFunction)(vector<double>diffs)); // should take other functions as args
   double calcMean(vector<double> diffs); // should be passed as argument
   double calcMeanMinMax(vector<double> diffs); // should be passed as argument
   double calcMedian(vector<double> diffs); // should be passed as argument
}

CutDetector.h

double thresholdForFrameIndex(int frameIndex, vector<double> diffs, int steps, double (CutDetector::*thresholdFunction)(vector<double>diffs)) {
    vector<double> window = ... init the window vector ;
    double threshold = thresholdFunction(window);
    return threshold;
}

但是,將thresholdFunction作為這樣的參數傳遞是行不通的。 編譯器抱怨以下錯誤:

錯誤 :稱為對象類型'double (CutDetector::*)(vector<double>)'不是函數或函數指針

誰能看到為什么我的設置不起作用,並提出如何使它起作用的建議? 基本上,我想要的是能夠將任何計算閾值的成員函數(即calcMeancalcMeanMinMaxcalcMedian )傳遞給其他成員函數thresholdForFrameIndex

要調用成員函數的指針,您需要提供一個對象:

double threshold = (this->*thresholdFunction)(window);
                   ^^^^^^^^                 ^

沒有類的實例,就不能調用成員函數。 您需要執行以下操作:

CutDetector cd;
double threshold = (cd.*thresholdFunction)(window);

或者,如果您在某處有一個CutDetector指針:

double threshold = (pcd->*thresholdFunction)(window);

或者,如果thresholdForFrameIndex是成員函數:

double threshold = (this->*thresholdFunction)(window);

我認為在這里使calcMeancalcMeanMinMaxcalcMedian 靜態函數與將其與所有其他非成員函數一樣對待會更容易。 其他答案是正確的,但對於您的情況,我想這對於班級設計會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM