No operator ">>" matches these operands operand types are: std::istream >> double
This might seem like a strange error message. After all, one could fairly quickly come up with an example program that streams a double
from std::cin
, which is a std::istream
. So what is wrong here?
The answer comes in that mess of notes that follows this error message. (Yes, it can be an intimidating mess, but the notes are there to help diagnosing the problem. No, I do not expect the entire mess to be copied into the question, since it is large and most of it is not relevant.) Somewhere in the list of candidate operators is
operator>>(double& __f)
This is the operator that allows streaming a double
. However, note the type of the parameter – it is not double
, but double&
. The target of the stream must name a variable, not merely provide a value. In your case, attempting in >> z.real()
is similar to attempting in >> 3.1
. The types of z.real()
and 3.1
are both double
, so what you can do to one you can do to the other. Hopefully you do not believe you can change mathematics by streaming a new value into 3.1
. Similarly, you cannot stream a value into a function that returns a double
.
One solution is to make your function return what the stream operator expects, as in double& real()
(add an ampersand and remove const
). However, providing a public non-const reference to a private member destroys encapsulation; the member might as well be public at that point. Plus, your project does not allow it. Let's look for a better approach.
A more common solution is to make operator>>
a friend
of your class so that it can set the private members. This requires adding the line
friend std::istream& operator>>(std::istream& in, complex& z);
to your class definition. After that is done, your implementation of operator>>
can access the private data members, bypassing the accessor functions. Note: the definition of operator>>
can stay right where it is, outside the class definition, if that is desirable.
std::istream& operator>>(std::istream& in, complex& z) {
in >> z.realX;
in >> z.imaginaryY;
return in;
}
A more roundabout approach uses construction and assignment instead of friendship. This might reduce code duplication in more complex cases. However, in your case it triggers a warning because your class violates the Rule of Three by having a copy constructor but no assignment operator. Still, your explicit copy constructor is what the compiler would automatically generate for you. You could address the warning by commenting out your copy constructor.
std::istream& operator>>(std::istream& in, complex& z) {
double real;
double imaginary;
in >> real;
in >> imaginary;
z = complex{real, imaginary};
return in;
}
For something as simple as your complex
class, I would go with friendship.