I have a class complex and I would like to operator << could print its private variables.
class complex
{
double re, im;
public:
friend ostream operator <<(ostream &out); // What's wrong?
};
Is it possible?
I have a class complex and I would like to operator << could print its private variables.
class complex
{
double re, im;
public:
friend ostream operator <<(ostream &out); // What's wrong?
};
Is it possible?
You have to pass two arguments into operator <<()
(a reference to the stream object and one to the object you want to stream) and you generally always want to return
a reference to the stream passed in so you can pass the output to another invocation of operator<<()
. So you need something like:
friend ostream& operator <<(ostream &out, const complex& rhs);
Object to be outputed must be passed as parameter:
friend ostream& operator <<(ostream &out, const complex& obj);
Then, you have to implement the function, possible like this:
ostream& operator <<(ostream &out, const complex& obj)
{
out << obj.re << ";" << obj.im;
return out;
}
yes it is possible but you make a mistake in operator parameter list, there is two parameter not one, one for ostream which the compiler automatically recognize it and in here it must be ostream, the second one will be the class type you will use after cout<<classType in here is Complex, by the way look at this cout<<Complex
cout is first parameter, so then you should use these code it will works.
#include <ostream>
using std::ostream;
class Complex
{
public:
friend ostream &operator <<(ostream &out, Complex &cmplx)
{
out << cmplx.im << "\t" << cmplx.re;
return out;
}
private:
double re, im;
};
int main()
{
Complex complex;
cout<<complex;
return 0;
}
it will print the value of re
and im
.