组合构造函数从成员变量中获取变量

composition constructor get variable from member variables

本文关键字:变量 获取 成员 构造函数 组合      更新时间:2023-10-16

我正在调用一个类(例如:B)作为另一个类的参数(例如:a)(composition)。我想告诉类B从类A的成员变量中获取构造函数变量。

这是boostodeint:的一个例子

lib.h

using namespace boost::numeric::odeint;
/* The type of container used to hold the state vector */
typedef vector<double> state_type;
/* The rhs of x' = f(x) defined as a class */
class harm_osc {
double m_gam;
public:
harm_osc( double gam ) : m_gam(gam) { }
void operator() ( const state_type &x , state_type &dxdt , const double /* t */ )
{
dxdt[0] = x[1];
dxdt[1] = -x[0] - m_gam*x[1];
}
};
/*------------------------------------------------------------*/
class osc_solver {

public:
osc_solver(const harm_osc &ho) : m_ho(ho) {
x = {1.0, 0.0}; // start at x=1.0, p=0.0
}
void run();
private:
harm_osc m_ho;
state_type x;
vector<state_type> x_vec;
vector<double> times;
};

lib.cpp

void osc_solver::run()
{
size_t steps = integrate(m_ho,
x, 0.0, 10.0, 0.1,
push_back_state_and_time(x_vec, times));
/* output */
for (size_t i = 0; i <= steps; i++)
{
cout << times[i] << 't' << x_vec[i][0] << 't' << x_vec[i][1] << 'n';
}
}

main.cpp

int main(int /* argc */ , char** /* argv */ )
{
osc_solver sol(harm_osc(0.15));
sol.run();
return 0;
}

我需要这样的东西:

osc_solver sol(0.15, harm_osc));

因为有时我需要将许多变量传递给我在这两个类中使用的类。

谢谢你的指导。

您可以用模板参数HarmType定义osc_solver类,该参数化成员osc_solver::m_ho的类型,并通过转发osc_solver的构造函数的参数来构造它。类似的东西

#include <utility>
template <class HarmType>
class osc_solver {
public:
template <class... ArgsType>
osc_solver(ArgsType&&... parameters_ham) : m_ho(std::forward<ArgsType>(parameters_harm)...) {
x = {1.0, 0.0}; // start at x=1.0, p=0.0
}
void run();
private:
HarmType m_ho;
state_type x;
vector<state_type> x_vec;
vector<double> times;
};

例如,您可以使用osc_solver对象作为

// harm_osc needs 1 parameter in the constructor
osc_solver<harm_osc> solver(0.15);
// harm_osc_special needs 2 parameters in the constructor
osc_solver<harm_osc_special> solver(0.15, 0.2);

更一般地说,您可以将osc_solver::osc_solver定义为需要类osc_solver和构造osc_solver:m_ho中使用的两个参数,如:

template <class HarmType>
class osc_solver {
public:
template <class... ArgsType>
osc_solver(double a, ArgsType&&... parameters_ham) : m_ho(std::forward<ArgsType>(a, parameters_harm)...)
{
// Here use parameter a
}
// ...