if you only need to provide a global function to export your class to std::cout, you can also import data from std::cin to your own class:
-sharpinclude <iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
istream & operator >> (istream &in, Complex &c)
{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part ";
in >> c.imag;
return in;
}
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
but now I need my own class to be able to get data through < <, such as the above class Complex:
class Complex;
Complex c;
c << 1;
suppose 1 is stored in real
now I"m giving "123" to object c, how do I write it?