简体   繁体   中英

Initialisation list and const reference

I've a question about initialisations lists and const elements. If i have declare "const Timestep& myTimestep" then it does not work (invalid arguments) and if I remove const it works. I is there something i missed? Thanks a lot

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

You have to define get_mesh as a const method because you declare Timestep in Solver as cost variable, then you are allowed to call only const methods:

int get_mesh() const;

Various error in your code, however this works :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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