【问题标题】:How to properly pass member function as argument in this situation in C++?在这种情况下,如何在 C++ 中正确地将成员函数作为参数传递?
【发布时间】:2015-07-17 18:19:09
【问题描述】:

我想将我的 C++ 类的成员函数传递给同一类的另一个成员函数。我做了一些研究,在 SO 上发现了这些类似的问题。

Passing a member function as an argument in C++

Function pointer to member function

他们没有以相同的方式涵盖我的具体案例,但我编写了我的代码并认为我调整了正确的部分以使其适用于我的情况。但是,编译器似乎不同意我的观点......

我的 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&lt;double&gt;)' 不是函数或函数指针

谁能看到我的设置为什么不起作用并建议我如何使它起作用?基本上我想要的是能够将任何计算阈值的成员函数(即calcMeancalcMeanMinMaxcalcMedian)传递给另一个成员函数thresholdForFrameIndex

【问题讨论】:

  • 1.那些 both 真的在 CutDetector.h 中吗,以及 2. 您是否有意省略了第二个 sn-p 定义中的 CutDetector:: 限定符(即,这是一个免费功能,而 不是 在前一个类中声明的成员)?
  • 您可能希望将 vector 作为 const & 传递以避免代价高昂的复制操作。

标签: c++ functional-programming function-pointers member-function-pointers


【解决方案1】:

要调用指向成员函数的指针,您需要提供一个对象:

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

【讨论】:

  • 谢谢,这似乎是我正在寻找的解决方案!但是,当完全使用这种语法时,编译器会再次抱怨 error: invalid use of 'this' outside of a non-static member function
  • @nburk 很好地回答了我在一般评论中提出的第二个问题。你需要一个实例。仍然不知道CutDetector:: 的遗漏是否是故意的。您是否看到您将该功能定义为 double thresholdForFrameIndex(...) 而不是 double CutDetector::thresholdForFrameIndex(...)
  • 啊,你说得对!这实际上是我的错,在我的.cpp-file 中我没有声明该函数是我班级的成员......现在它可以工作了! :)
【解决方案2】:

没有类的实例就不能调用成员函数。你需要做这样的事情:

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

或者如果你在某处有一个CutDetector 指针:

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

或者如果thresholdForFrameIndex是一个成员函数:

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

【讨论】:

    【解决方案3】:

    我认为在这里创建calcMeancalcMeanMinMaxcalcMedian 静态 函数并像对待所有其他非成员函数一样处理会更容易。其他答案是正确的,但在你的情况下,我想这对类设计会更好。

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      相关资源
      最近更新 更多