The symbol << is used to represent both the stream insertion operator and a bitwise left shift. You have to be a little careful using both since it can get confusing.
cout << 5 << 2 << endl;
cout << (5 << 2 ) << endl;
We are focusing on the use as the stream insertion operator. We will look at the overloading and then briefly explain why it works, the details will make more sense later in the subject.
To overload the << operator so it can work with a class object, you must add the overloaded operator<<() function to the class as a friend.
friend ostream& operator<<(ostream&, const className&);
ostream& operator<<(ostream& sOut, const ComplexNumber &cN)
{
sOut << cN.real <<"+" << cN.img <<"i";
return sOut;
}
sOut << cN.real << " " << cN.img;
ComplexNumber num1(3,4);
cout << num1 << endl;
It’s better not to put the << endl; in the overloaded operator.
That would be inconsistent with the typical use of cout for built in objects.
To overload the >> operator so it can work with a class object, you must add the overloaded operator>>() function to the class as a friend.
friend istream& operator>>(istream&, className&);
istream& operator>>(istream& sIn, ComplexNumber &cN)
{
sIn >> cN.real >> cN.img;
return sIn;
}
ComplexNumber num1;
cin >> num1;