Overloading Stream Insertion and Extraction Operators
This video tutorial made by the Learning Lad youtube chanel explains how to Overload Stream Insertion and Stream Extraction Operators in c++.
You will learn what is the syntax to overload stream insertion and stream extraction operators, how to make stream insertion and extraction operators to work with a user defined custom class, how to define the stream insertion and extraction operators as friend to a class, how to write the operator function in detail with example.
source code for this tutorial
#include <iostream> #include <string> using namespace std; class Person{ string name; int age; public: Person(){ name = "noname"; age = 0; } friend ostream &operator << (ostream &output,Person &p); friend istream &operator >> (istream &input, Person &p); }; ostream &operator << (ostream &output,Person &p){ output << "what the hack "<<endl; output << "my name is "<< p.name << " and my age is "<<p.age << endl; return output; } istream &operator >> (istream &input,Person &p){ input >> p.name >> p.age; return input; } int main() { cout << "enter the name and age "<<endl; Person anil; cin >> anil; cout << anil; return 0; }