[英]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.