组合构造函数从成员变量中获取变量
composition constructor get variable from member variables
我正在调用一个类(例如: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
}
// ...
相关文章:
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 使用递归时获取变量的奇怪值
- 从 C 中的变量获取文件的路径,C++
- 我可以从其变量中获取对类对象的引用吗?
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 如何使用可变参数模板获取参数的变量号及其大小C++
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- constexpr 函数在编译时获取值,即使我的变量不是 constexpr
- 如何在不为其声明变量的情况下获取和使用常量值的地址?
- 附加调试器并以编程方式获取变量地址 Visual Studio
- 是否可以将变体的索引作为 constexpr 变量获取?
- 为什么我无法获取 MSVS2019 / C++ 中字符或uint8_t变量的内存地址?
- 我正在尝试获取类私有成员中变量的输入
- C++/Win32 构造函数不使用从对话框获取的字符串初始化变量
- 使用基地址和偏移量获取变量的地址
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- 使用 WindowSetup 类变量获取错误
- fstream 变量获取文本文件中的所有行
- 从类型而不是从变量获取指针级别