2012-07-02 141 views
0

我的情况如下,我有两个不同的平分函数,在我的代码中的某个点将被调用。基本上有些函数调用Bisection2,该函数调用传递的函数或将函数指针传递给Bisection函数。传递成员函数指针

在标头,我

std::vector<double> F(); 
double F1(double m1, double m2); 
double F2(double m1, double m2); 
typedef double (MyClass::*MyClassFn)(double,double); 
double Bisection(MyClassFn fEval,double min, double max,std::vector<double> args); 
bool Bisection2(MyClassFn fEval1,MyClassFn fEval2,double xmin, double xmax, double ymin, double ymax,double *ax, double *ay,std::vector<double> args); 

而我的二分功能如下所示。我没有包含所有的代码,因为它没有必要。

double MyClass::F1(double m1, double m2) { 
    m_m1 = m1; 
    m_m2 = m2; 
    F(); 
    return m_my; 
} 

double MyClass::F2(double m1, double m2) { 
    m_m1 = m1; 
    m_m2 = m2; 
    F(); 
    return m_mx; 
} 
double MyClass::Bisection(MyClass fEval,double min, double max,std::vector<double> args) 
{ 
    // Setting a lot of stuff here, including auxiliary and leftvalue... 

    MyClass *pObj = new MyClass(-1); 

    leftvalue = pObj->*fEval(auxiliary, left); 
    ightvalue = pObj->*fEval(auxiliary, right); 

    // Comparing and setting values here etc. 
} 
bool MyClass::Bisection2(MyClassFn fEval1,MyClassFn fEval2,double xmin, double xmax, double ymin, double ymax,double *ax, double *ay,std::vector<double> args) 
{ 

    // Setting some values here but these have nothing to do with the problem. 
    double yl; 
    double leftvalue, rightvalue, middlevalue; 

    MyClass *pObj = new MyClass(-1); 

    // Setting some values here but these have nothing to do with the problem. 
    std::vector <double> arg; 
    // pushing some values 

    yl = Bisection(fEval2,ymin,ymax,arg); // Here is the first way how I need to pass fEval2 to Bisection function. 
    arg.clear(); 

    if(isnan(yl)) 
    { 
     return M_NAN; 
    } 
    leftvalue = pObj->fEval1(xl, yl); // And here is the second way how I need to use fEval1. 

//..... 
} 

然后,我已经基本功能什么叫

`Bisection2(F1,F2,m_m2,0.0,0.0,m_max2,& m_mu1,& m_mu2,参数);

Bisection2(...)调用此时可能不正确,因为自上次工作以来,我已经更改了很多功能。上次我基本上直接在函数内部调用F1和F2函数指针而不是fEval,但我确信这是不正确的方式,毕竟即使它认为它似乎工作。

现在leftvalue = pObj - > * fEval(auxiliary,left);导致编译错误:

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘fEval (...)’, e.g. ‘(... ->* fEval) (...)’ 

我想看看帮助从这里http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2 还检查了这些论坛,也许不同的解决问题,但仍然无法弄清我做错了。

谢谢。

+0

在'Bisection'参数'的*定义* fEval'被声明为具有'MyClass'类型。这是不正确的。它应该是'MyClassFn',因为它在'Bisection'的声明中。 – AnT

回答

4

正如错误消息所述,您需要括号。这是因为该函数调用比->*运营商更高的优先级:

leftvalue = (pObj->*fEval)(auxilary, left); 
      ^  ^

而且,你几乎肯定不应该在这里使用new;

MyClass obj(-1); 
leftvalue = (obj.*fEval)(auxiliary, left); 
+0

非常感谢你!说实话,我通过重写和调试这些函数(几天)而花费了大量的时间。起初我应该问这个问题是因为这基本上是我第一次使用这些函数的方法-_- – Mare2

0

这简直是一个优先事项:您可以使用自动存储解决内存泄漏 而不是做pObj->*fEval(aux, left),只是做(pObj->*fEval)(aux, left)