Список инициализации и константная ссылка

0

У меня вопрос о списках инициализации и элементах 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
    &this ? Я думаю, что вы имели в виду *this
Теги:
initialization
const

1 ответ

0
Лучший ответ

Вы должны определить get_mesh как метод const, потому что вы объявляете Timestep в Solver как переменную стоимости, тогда вам разрешено вызывать только методы 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;
}
  • 0
    Спасибо, проблема решена. Почему бы &this ? Я получаю ошибку с использованием указателя ( *this ). Кроме того, конструктор хочет ссылку, а не указатель.
  • 0
    @dani: (* this) не указатель, а фактически объект Timetep. Как насчет вашей ошибки?
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню