'non-static reference member, can't use default assignment operator'

别说谁变了你拦得住时间么 提交于 2021-01-22 12:13:49

问题


I get this error when i try to compile my code: non-static reference member ‘Timestep& Timestep::previousTimestep’, can’t use default assignment operator

I create one Problem which creates a Timestep a reference to the this Timestepshould be stored in the vector solution. Besides i want to store a reference to a previous Timestep - and for the first Timestep that would be a reference to itself...

I read that i need to define an own operator if i have const members in a class what i try to set equal. However, removed all const elements form the code and it still don't work. Any suggestions? Thanks a lot.

class Problem {
public:
    void initialTimestep(arma::vec ic);
private:
    std::vector<Timestep> solution;
};

void Problem::initialTimestep(vec ic){
    Timestep myFirstTimestep(starttime, ic, nodes);
    solution.push_back(myFirstTimestep);
}



class Timestep {
public:
    Timestep(double starttime, arma::vec initialCondition, arma::vec nodelist);
private:
    Timestep& previousTimestep; //const
};

Timestep::Timestep(double starttime, vec initialCondition, vec nodelist)
: previousTimestep(*this)
    {
    //do stuff
}


int main() {
    int k = 3; //subdomains
    vec v = linspace(0., 1., k+1); //node spacing
    vec ic= ones<vec>(k+1); //initialconditions
    Problem myProblem(v, ic, 0., 1., 0.1);
    return 0;
}

回答1:


No default assignment operator was created for your class Timestep because it contains a reference (which cannot be set later. it basically is a constant pointer to non-const data). solution.push_back(myFirstTimestep) requires the asignment though (or move with c++11) so you will have to define your own assignment (or move) operator (which of course you will not be able to do unless you change Timestep& previousTimestep to Timestep *previousTimestep in which case the default assignment will work as well).




回答2:


You need to write your own assignment operator for the Timestep class (operator=).

Alternatively, you can use a Timestep pointer instead of a reference inside the Timestep class. That'd be my personal preference in this case. The compiler imposes a lot fewer rules about pointers, for various reasons.



来源:https://stackoverflow.com/questions/22437903/non-static-reference-member-cant-use-default-assignment-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!