How does CPP get its class to provide the < < operator

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?

CPP
Jun.09,2022

I don't know if that's what you mean. Just overload it with the identifier of CPP. Overload the sign. Here's a simple example code

.
-sharpinclude <iostream>
using namespace std;
class Complex
{
public:
    float real;
    void operator <<(float r)
    {
        real = r;
    }
};
int main()
{
    Complex c;
    c << 1.5;
    cout<<c.real;
    return 0;
}
Menu