我有一个带有子类的基类Method
。
auto harmonic_force = [](const double& q, const double& k){return -k*q;};
enum SplittingAB{ SS,L42 };
class Method
{
public:
~Method() = default;
virtual void evolute( std::vector<std::pair<double,double>> &qp, int T) const = 0;
};
template <typename Function>
class MiddleO : public Method{
public:
MiddleO() = default;
explicit MiddleO(SplittingAB mmo_=SS, const double& a_=-1.0, const double& b_=1.0, const Function& force_=harmonic_force, const double& k_=1.0, const double& gamma_=1.0, const double& kBT_=1.0);
void evolute( std::vector<std::pair<double,double>> &qp, int T) const override;
std::string get_name(SplittingAB m) const {
switch (m){
case SplittingAB:: SS:{
return "MethodsMiddleO_SS";
}
case SplittingAB ::L42:{
return "MethodsMiddleO_L42";
}
}
}
private:
SplittingAB mmo;
const double k{}, gamma{}, kBT{}, a{}, b{};
double L = 1.0;
Function& force;
};
我对构造函数的定义如下:
template<typename Function>
MiddleO<Function>::MiddleO(SplittingAB mmo_, const double &a_, const double &b_, const Function &force_,
const double &k_, const double &gamma_, const double &kBT_)
: Method(), mmo(mmo_), a(a_), b(b_), force(force_), k(k_), gamma(gamma_), kBT(kBT_) { L=b-a; }
binding reference of type ‘<lambda(double, double)>&’ to ‘const<lambda(double, double)>’ discards qualifiers
。我不明白如何正确初始化力。Constructor does not initialize these fields: mmo
编辑:在我的main()
函数中,我写道:
auto cos_force = [](double q, const double k){return -q*q*q*k - 5.0*cos(1+5.0*q);};
int main(){
double a = -3.5;
double b = 3.5;
double const k = 1.0;
double const gamma = 1.0;
double const kBT=1.0;
std::vector<std::pair<double,double>> qp;
qp.reserve(T+1);
qp.emplace_back(0.0,0.1);
SplittingAB sm = SS;
MiddleO<decltype(cos_force)> obj(sm, a, b, cos_force , k, gamma,kBT);
...
}
编译器正确地报告了一个错误,因为您试图将Function&
初始化为Function const&
。如果允许,它将不会保留原始对象的const
样式。
除非性能是用例的公认问题,否则更改
Function& force;
到
Function force;
添加代码以初始化成员。
template<typename Function>
MiddleO<Function>::MiddleO(SplittingAB mmo_, const double &a_, const double &b_,
const Function &force_, const double &k_,
const double &gamma_, const double &kBT_)
: Method(), mmo(mmo_), a(a_), b(b_), force(force_), k(k_),
gamma(gamma_), kBT(kBT_), mmo(SS) { L=b-a; }
// ^^^^^^^
也许编译器抱怨默认构造函数。
也,
MiddleO() = default;
不正确。这没有为引用成员提供初始化方法。编译器应该为此报告一个错误。