I've been trying to overload the >>
operator. I have a class that has two private variables:
Class Complex
{
private:
double real;
double imaginary;
};
In addition I have a friend function that overloads the >>
operator:
friend istream & operator>>(istream &is, Complex &c)
In the implementation of the function I've tried many ways to write into the variable of object c
but I keep getting an error no operator >> matches these operands
I looked around and read that I need to write into a reference
of the variable, so I tried the following:
istream & operator>>(istream &is, Complex &c)
{
using std::cout;
double &r = c.real;
cout << "real: " << is >> r;
return is;
}
However this still gives me the same error.
I'm slightly confused as I tried is >> c.real
and didn't work.
On one of the answers in a similar SO question, someone suggested writing into a local variable and setting the object variable it, something like:
double d;
cin >> d;
setReal(d);
I'm trying to find a more simpler way to achieve this rather than using a method or setting the variable to a local one.
The solution could be a simple one, but I'm really just a beginner in C++, so please take it easy on me :P.
Test case:
using std::cin;
Complex c;
cin >> c;
Exact error message:
Error 1 error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::basic_ostream<_Elem,_Traits>' (or there is no acceptable conversion)
The error is on this line:
cout << "real: " << is >> r;
This is interpreted as
((cout << "real: ") << is) >> r
The problem here is that you can't have a line like this where you switch from outputting to cout
and start reading from is
. A better way to do this would be
cout << "real: ";
is >> r;
That said, this is a very bad idea. You should not have operator >>
display a prompt, since it means that if you want to read in an object of your type from a file, every time you do so you will get the prompt "real
" displayed on-screen. You should have operator >>
just read the representation, and explicitly prompt before reading if that's what you want to do.
Hope this helps!