首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >初始化列表和const引用

初始化列表和const引用
EN

Stack Overflow用户
提问于 2014-03-15 17:24:20
回答 1查看 47关注 0票数 0

我有一个关于初始化列表和const元素的问题。如果我声明了"const & myTimestep“,那么它就不能工作(无效的参数),如果我删除了它,它就会工作。我错过了什么吗?非常感谢

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-15 17:46:27

您必须将get_mesh定义为const方法,因为您在Solver中将时间步骤声明为成本变量,然后只允许调用const方法:

代码语言:javascript
复制
int get_mesh() const;

但是,您的代码中出现了各种错误,但是这样做是有效的:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22427195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档