Search code examples
c++operator-overloadinginsertion

Input/Output Operators Overloading in C++


Stuck with ostream/istream operator overloading Q1. why we are using ostream& operator as friend? Q2. Why we are passing two arguments in ostream & operator << (ostream &out, const Complex &c) Q3. why we are referencing to Cout and in ? istream & operator >> (istream &in, Complex &c).

Ref to: Overloading stream Oerator overloading- Geeks4Geeks

HERE IS THE CODE

#include <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 Imaginary Part "; 
    in >> c.imag; 
    return in; 
} 

int main() 
{ 
Complex c1; 
cin >> c1; 
cout << "The complex object is "; 
cout << c1; 
return 0; 
}


Solution

  • A1. To access the private members

    A2. The first argument is the stream and the second is the object. operator<< and operator>> expect two arguments

    A3. Because they are modified in the function. The functions read from resp. write into the stream.

    In addition:

    • Don't use using namespace std;
    • Don't initialize members in the constructor body. Use the constructor initializer list

      Complex(int r = 0, int i =0) 
      { real = r; imag = i; } 
      

      should be

      Complex(int r = 0, int i = 0) : real(r), imag(i) {}