我必须在一些库中工作,无论我做什么,我都会在这段代码中出现以下错误。
传递`const amko :: problem :: launch'作为'const double amko :: problem :: launch :: ratio(double,double)'的'this'参数'丢弃限定符
namespace amko { namespace problem {
launch::launch():base( 0.0, 20.0, 1 ) {}
base_ptr launch::clone() const
{
return base_ptr(new launch(*this));
}
const double launch::ratio( const double a, const double b)
{
const double area = a*b;
const double circumference = 2*a+2*b;
const double ratio = circumference/area;
return ratio;
}
void launch::objfun_impl(fitness_vector &f, const decision_vector &xv) const
{
amko_assert(f.size() == 1 && xv.size() == get_dimension());
const double x = xv[0];
const double y = launch::ratio(x,5);
f[0] = y;
}
虽然下面的代码工作得很好。
namespace amko { namespace problem {
initialValueProblem::initialValueProblem():base( 0.0, 20.0, 1 ) {}
base_ptr initialValueProblem::clone() const
{
return base_ptr(new initialValueProblem(*this));
}
Eigen::VectorXd initialValueProblem::computeDerivative( const double time, const Eigen::VectorXd& state )
{
Eigen::VectorXd stateDerivative( 1 );
stateDerivative( 0 ) = state( 0 ) - std::pow( time, 2.0 ) + 1.0;
return stateDerivative;
}
void initialValueProblem::objfun_impl(fitness_vector &f, const decision_vector &xv) const
{
amko_assert(f.size() == 1 && xv.size() == get_dimension());
const double x = xv[0];
double intervalStart = 0.0;
double intervalEnd = 10.0;
double stepSize = 0.1;
Eigen::VectorXd initialState_;
initialState_.setZero( 1 );
initialState_( 0 ) = x;
numerical_integrators::EulerIntegratorXd integrator( boost::bind( &initialValueProblem::computeDerivative,
const_cast<initialValueProblem*>( this ), _1, _2 ), intervalStart, initialState_ );
Eigen::VectorXd finalState = integrator.integrateTo( intervalEnd, stepSize );
f[0] = fabs( finalState( 0 ) - 11009.9937484598 );
}
谢谢!
答案 0 :(得分:2)
launch::objfun_impl
是const
成员函数,它不能更改成员或调用其他函数。这意味着它无法调用非const
非static
成员函数,例如launch::ratio
。
因为launch::ratio
似乎根本不访问成员,只是它的参数,最简单的解决方法是通过更改类定义中的原型使其成为static
成员函数:
static /* <- ADDED static HERE */ double launch::ratio(const double a, const double b);
答案 1 :(得分:0)
问题是你的ratio
成员函数不是const
,即使你没有修改对象的任何成员(为什么它根本就是成员函数?)。在objfun_impl
内,您正在调用ratio
。现在,objfun_impl
为const
,因此承诺不会修改对象,但调用ratio
会破坏该承诺。