首页 > 解决方案 > 组合构造函数从成员变量中获取变量

问题描述

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

这是 boost 的一个例子odeint

库文件

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;
};

库文件

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';
    }
}

主文件

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

我需要这样的东西:

osc_solver sol(0.15, harm_osc));

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

感谢您的任何指导。

标签: c++odeint

解决方案


您可以osc_solver使用模板参数定义类,该模板参数HarmType化成员的类型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_solveras的对象

// 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为需要在 classosc_solver和 constructor中使用的两个参数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
    }
 // ...

推荐阅读