DEV Community

Cover image for I/O Stream or Shift Operators Overloading | C++
Yash Desai
Yash Desai

Posted on

I/O Stream or Shift Operators Overloading | C++

The Data class

#include <iostream>
using namespace std;

class Data
{
private:
    int n, m;
public:
    Data() { n = 0; m = 0; }
    Data(int n, int m) { this->n = n; this->m = m; }

    //stuff for ostream operator << ...
    //stuff for istream operator >> ...
};
Enter fullscreen mode Exit fullscreen mode

Inside "Data" class...

    friend ostream &operator<<(ostream &myout, Data &data)
    {
        myout << "n: " << data.n << " m: " << data.m << endl;
        return myout;
    }
    friend istream &operator>>(istream &myin, Data &data)
    {
        myin >> data.n;
        myin >> data.m;

        return myin;
    }
Enter fullscreen mode Exit fullscreen mode

Now the main()

int main()
{
    Data data(5, 7);
    Data data1;

    cout << data;

    cin >> data1;

    cout << data1;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

Also available on YouTube

Top comments (0)