let us assume I have a class with
#include <iostream>
using namespace std;
class Test{
public:
friend istream& operator >> (istream& input, Test& test){
input >> test.dummy;
return input;
};
friend ostream& operator << (ostream& output, Test& test){
output << test.dummy << endl;
return output;
};
private:
const int dummy;
}
This does not work because dummy is constant. Is there a way to load from file and recreate an object with parameters which are constant?
Use const_cast. Usually you use it for objects that outside look like if they are constant, but internally they do need to update state every now and then. Using it for reading from stream is a little confusing, to say the least.
friend istream& operator >> (istream& input, Test& test){
input >> const_cast<int&>(test.dummy);
return input;
};
Ditch stream operator, use a factory function.
static Test fromStream(istream& input) {
int dummy;
input >> dummy;
return Test(dummy);
}
Ditch const. Instead, pass your entire object as const if needed.
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