繁体   English   中英

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

[英]composition constructor get variable from member variables

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

这是来自boost odeint的示例:

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

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

感谢您的指导。

你可以定义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_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
    }
 // ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM