how to overload stream operators in c++ | overloading insertion and extraction operator

preview_player
Показать описание
Overloading stream operators in c++
• As we can overload any other operator similarly we can overload stream operators (insertion operator and extraction operator).
• The stream operators can be overloaded only using friend function. They cannot be overloaded using the member function, because their first operand is always stream object.
• When we overload the insertion operator (<<) then the operator function takes two arguments , the first argument is a reference to the ostream class object and second argument is an object of the class for which we are defining operator function. The overloaded operator function returns a reference to the ostream class object.
• Syntax of definition:
ostream & operator <<(ostream& objectname,Classname objectname)
{_______;
_______;
}
• When we use the overloaded operator in between cout and object of the class, then the operator function is automatically called, and both cout and second operand object is passed as argument.
• When we overload the extraction operator (>>) then the operator function takes two arguments, the first argument is a reference to the istream class object and second argument is a reference of object of the class for which we are defining operator function. The overloaded operator function returns a reference to the istream class object.
• Syntax of definition:
istream & operator >>(istream& objectname,Classname &objectname)
{_______;
_______;
}
• When we use the overloaded operator in between cin and object of the class, then the operator function is automatically called, and both cin and second operand object is passed as argument.

Q: WAP to overload stream operators for Student class.

#include<iostream>
using namespace std;
class Student
{ char name[20];
int roll;
friend ostream & operator <<(ostream &,Student);
friend istream & operator >>(istream &,Student &);
};
ostream & operator <<(ostream &out,Student s1)
return out;
}
istream & operator >>(istream &in,Student &s1)
{ cout<<"\nName : ";
cout<<"\nRoll number : ";
return in;
}
int main()
{
Student s1;
cout<<"Enter details of object\n";
cin>>s1;//operator >>(cin,s1)
cout<<"Details are\n";
cout<<s1;//operator <<(cout,s1)
return 0;
}
Рекомендации по теме
Комментарии
Автор

Ostream ka reference ku pass kiya sirf object ku nahi ku ki object pass karke bhi to cascading ho sakti h or object pass karne pe error aata h aisa ku

jugalgoswami