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 Timestep
should 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;
}
Default Assignment Operator and References in C++ In this article, we discussed that when we don't write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems.
Implicitly-defined copy assignment operator For non-union class types (class and struct), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and copy assignment operator for class types.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With