This may be a novice question, but I can’t figure it out by inspecting the book I have.
The class’s constructor initializes two doubles, and I want the following code to output those two doubles with <<.
Complex x( 3.3, 1.1 );
cout << "x: " << x;
After this I need to overload >> to accept two doubles into these.
This is my first question here, so if my information provided is lacking inform me
EDIT:
I now have for the constructor and overloading statement this:
#include "Complex.h"
Complex::Complex( double realPart, double imaginaryPart )
: real( realPart ),
imaginary( imaginaryPart )
{
}
std::istream& operator>>(std::istream& strm, const Complex &c)
{
double r,i;
strm >> r >> i;
c = Complex(r,i);
return strm;
}
I know I have to change the “const Complex &c” and the “c = Complex(r,i);” but I’m not sure how to go about it.
Also, I will say here that this is not about the std library’s Complex class, although it is based on the same idea. So far everyone has been a great help, but I have a case of the dumb today.
operator<< :
std::coutis anstd::ostreamobject, so you have to overloadoperator<<forostream, which takesstd::complex<double>as an argument, assuming you usestd::complex<double>from the standard header complex. Since you shouldn’t make internal changes to standard containers and classes, make it standalone.operator>> :
operator>>takes astd::istreamobject, which does the opposite of whatstd::ostreamdoes. If you use streams for serialization like this, it’s a good idea to enable exceptions for them too. Usually you only want to throw onstd::ios::badbit.If you needed access to internal members of the class, you would define the overloaded function as a friend. But since std::complex::real() and std::complex::imag() are a part of the public interface, that’s not needed here. And for the istream example, we simply invoke the copy-constructor which is also a part of the public interface.
I assumed you wanted to use cin and cout here. But if you wanted to overload the operators for something else, the same applies. If you implement the operators inside a class definition, you have access to the
thispointer, hence the operator function should only take one argument.