我是C ++编程的新手(但更多地用于IDL和Python)。我实际上是在尝试将我已用IDL编写的代码重写为C ++,以提高其效率。在我的项目中,我希望从另一个类中调用类中的函数。下面,我复制了我认为理解问题所需代码的基本部分。但是,我对其进行了简化,以提高其清晰度。
使用g ++编译时,我收到以下错误:
MALA.cpp: In member function ‘void MALA::update_position_MH(Model_def*, Data*, Config*, int)’:
MALA.cpp:277:52: error: no matching function for call to ‘Model_def::call_model(Data&)’
propos_model=(*model_class).call_model(*data_struc); // PROBLEM HERE! TO DEBUG!
^
In file included from MALA.h:13:0,
from MALA.cpp:29:
model_def.h:34:12: note: candidate: Eigen::VectorXd Model_def::call_model(Data*)
VectorXd call_model(Data *data_struc); // call a model using its name
^
model_def.h:34:12: note: no known conversion for argument 1 from ‘Data’ to ‘Data*’
我不明白的是,如果我对该行进行注释(参见给定代码的最后一部分),代码编译时没有错误:
propos_model=(*model_class).call_model(*data_struc); // PROBLEM HERE!
但是,为什么我没有得到错误的一行:
vars_new=new_prop_values((*model_class).vars, m); // This works fine
传递结构时,我做错了什么?数据'作为函数call_model的参数?
这是简化的代码,分布在不同的文件中:
这是model_def.h(简化)
#include <Eigen/Dense>
#include <string>
#include "config.h"
#include "data.h"
class Model_def{
string model_name;
bool relax[];
int plength[];
VectorXd cons;
long Ncons, Nvars, Nparams;
string vars_names[];
string cons_names[];
string params_names[];
public:
Model_def(string m_name, bool rlx[], int plgth, VectorXd params_in, string params_in_names); // The constructor
Eigen::VectorXd params;
Eigen::VectorXd vars;
Eigen::VectorXd call_model(Data *data_struc);
};
这是model_def.cpp(简化)
#include <Eigen/Dense>
#include <iostream>
#include <iomanip>
#include "model_def.h"
Eigen::VectorXd Model_def::call_model(Data *data_struc){
bool passed=0;
if(model_name == "Model_MS_Global"){
passed=1;
return Model_MS_Global(params, plength, (*data_struc).x); // This function is in a dedicated cpp file (not shown here)
}
// Other things happening...
}
这是data.h
#include <Eigen/Dense>
#include <string>
struct Data{
Eigen::VectorXd x;
Eigen::VectorXd y;
long Nx; // Ny is not checked but should be as long as x
string xlabel[];
string ylabel[];
};
这是MALA.h(简化)
#include <Eigen/Dense>
#include <string>
#include "model_def.h"
class MALA{
private:
int seed; // to generate random numbers
double epsilon1;
Eigen::MatrixXd epsilon2;
double A1;
double delta;
double delta_x;
public:
void update_position_MH(Model_def *model_class, Data *data_struc, Config *cfg_class, int m);
};
这是MALA.cpp(简化)
void MALA::update_position_MH(Model_def *model_class, Data *data_struc, Config *cfg_class, int m){
VectorXd vars_new;
double* u=uniform_01(1, &seed ); // Generate uniform random number between 0 and 1
VectorXd propos_model;
if((*cfg_class).proposal_type == "Random"){
vars_new=new_prop_values((*model_class).vars, m); // This works fine
}
propos_model=(*model_class).call_model(*data_struc); // PROBLEM HERE!
}
答案 0 :(得分:1)
data_struc是一个指针,call_model想要一个指针,所以你直接传递它。把*放在前面“取消引用”它并使它不再是指针。
propos_model=(*model_class).call_model(data_struc);
或者,好一点
propos_model = model_class->call_model(data_struc);