hi have had a look and searched but i couldnt find anything on iostream overloaded operators
so i was wondering if anyone on here could explain what this actually is?
Thanks
Printable View
hi have had a look and searched but i couldnt find anything on iostream overloaded operators
so i was wondering if anyone on here could explain what this actually is?
Thanks
The stream operators are designed from the get go to operate on the built in types: int, char, float, etc... For example:
Overloading these operators allows you to extend this capability to user defined types (custom class/struct objects).Code:int foo;
cin >> foo; // Read from cin stream into an integer
float bar = 12.9f;
cout << bar; // Write to cout stream converting from a float
Example I/O:Code:#include <string>
#include <iostream>
using namespace std;
struct person
{
string first_name;
string last_name;
int age;
person() {}
person(const string& fname, const string& lname, int yrs) : first_name(fname), last_name(lname), age(yrs) {}
};
// Overloaded stream extraction operator
istream& operator>>(istream& is, person& per)
{
return is >> per.first_name >> per.last_name >> per.age;
}
// Overloaded stream insertion operator
ostream& operator<<(ostream& os, const person& per)
{
return os << "First Name: " << per.first_name << "\nLast Name : " << per.last_name
<< "\nAge : " << per.age;
}
int main()
{
person h_simpson("Homer","Simpson",40);
//Output to cout using overloaded stream insertion operator<< for custom object of type person
cout << h_simpson << endl;
person temp;
// Read from cin using overloaded stream extraction operator>> for custom object of type person
cin >> temp;
cout << temp << endl;
return 0;
}
Code:First Name: Homer
Last Name : Simpson
Age : 40
Marge Simpson 38
First Name: Marge
Last Name : Simpson
Age : 38