I have a class that looks something like this:
#include <iostream>
class A {
public:
A (std::istream& is): _is(is) {}
void setInputSource (std::istream& is) {
_is = is;
}
A& operator>> (int& x) {
_is >> x;
return *this;
}
private:
std::istream& _is;
};
And I want the member to _isact as a link. I mean, it should "point" to the external one std::istream, and I do not want the method to setInputSource()copy the stream that is passed as an argument. The problem is that the program will not compile, because this method, which I mentioned, is trying to access the operator=class std::basic_istream<char>.
My goal is to make the class behave as expected in such a program:
int main() {
int a, b;
std::ifstream ifs("myfile.txt");
A myA(std::cin);
myA >> a;
myA.setInputSource(ifs);
myA >> b;
return 0;
}
I thought of using pointers instead, but I prefer to use references, because I like the fact that they guarantee that they will not have invalid values, and it seems to me that this is a more elegant approach.