[英]Passing a member function pointer(s)
我的情况如下,我有两个不同的二等分函数,它们在我的代码中的某个时候会被调用。 基本上,有些函数调用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,args);
目前,Bisection2(...)调用可能不正确,因为自上次工作以来,我已经对函数进行了很多更改。 上次我基本上直接在函数内部而不是fEval调用了F1和F2函数指针,但我相当确定这毕竟是不正确的方式,甚至认为它似乎可以正常工作。
现在leftvalue = pObj-> * fEval(辅助,左); 导致编译错误:
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寻求帮助,并且还在这些论坛中检查了可能已解决的不同问题,但仍然可以弄清楚我在做什么错。
谢谢。
如错误消息所述,您需要括号。 这是因为函数调用的优先级高于->*
运算符:
leftvalue = (pObj->*fEval)(auxilary, left);
^ ^
另外,您几乎可以肯定不应该在这里使用new
。 您可以使用自动存储来修复内存泄漏:
MyClass obj(-1);
leftvalue = (obj.*fEval)(auxiliary, left);
这只是一个优先事项:不用做pObj->*fEval(aux, left)
,而要做(pObj->*fEval)(aux, left)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.