我对初始化列表和const元素有疑问。如果我声明“const Timestep& myTimestep”然后它不起作用(无效的参数),如果我删除const它工作。我在那里错过了什么?非常感谢
HEADER______Solver.h____________
class Timestep; //forward declaration
class Solver {
public:
Solver(const Timestep &theTimestep)
void findSolution();
private:
const Timestep& myTimestep; //works perfectly if i remove const!
};
SOURCE______Solver.cpp_________
#include "Timestep.h"
#include "Solver.h"
Solver::Solver(const Timestep& theTimestep) : myTimestep(theTimestep)
{ }
Solver::findSolution(){
vec mesh = myTimestep.get_mesh(); //a memberfunction of Timestep
//and do more stuff
}
HEADER______Timestep.h____________
class Solver; //forward declaration
class Timestep{
public:
Timestep();
vec get_mesh(); //just returns a vector
...
}
SOURCE______Timestep.cpp_________
#include "Timestep.h"
#include "Solver.h"
Timestep::Timestep()
{
Solver mySolver(&this);
}
Timestep::get_mesh(){
return something;
}
MAIN_______main.cpp_____________
#include "Timestep.h"
#include "Solver.h"
main(){
Timestep myTimestep;
}
答案 0 :(得分:0)
您必须将get_mesh定义为const方法,因为您在Solver中将Timestep声明为成本变量,然后您只能调用const方法:
int get_mesh() const;
代码中存在各种错误,但这有效:
class Timestep{
public:
Timestep();
int get_mesh() const; //just returns a int
};
class Solver {
public:
Solver(const Timestep &theTimestep);
void findSolution();
private:
const Timestep& myTimestep; //works perfectly if i remove const!
};
Solver::Solver(const Timestep& theTimestep) : myTimestep(theTimestep) {}
void Solver::findSolution()
{
int mesh = myTimestep.get_mesh(); //a memberfunction of Timestep
//and do more stuff
}
Timestep::Timestep()
{
Solver mySolver(*this);
}
int Timestep::get_mesh() const
{
return 0;
}
int main(){
Timestep myTimestep;
}