Provides specialized output mechanisms for an object.
Overloading
inserter prototype
basic_ostream &oerator<<
(basic_ostream &stream,const omanip<T>&){
// procedures;
return stream;
}
You may overload the inserter operator to tailor it to the specific needs of a particular class.
The this pointer is returned.
#include <iostream> #include <string.h> #include <iomanip> class phonebook { friend ostream &operator<< (ostream &stream, phonebook o); protected: char *name; int areacode; int exchange; int num; public: phonebook(char *n, int a, int p, int nm) : areacode(a), exchange(p), num(nm), name(n) {} }; int main() { using namespace std; phonebook a("Sales", 800, 377, 5416); phonebook b("Voice", 512, 873, 4700); phonebook c("Fax", 512, 873, 4900); cout << a << b << c; return 0; } std::ostream &operator<<(std::ostream &stream, phonebook o) { stream << o.name << " "; stream << "(" << o.areacode << ") "; stream << o.exchange << "-"; stream << setfill('0') << setw(4) << o.num << "\n"; return stream; }
Result:
Sales (800) 377-5416 Voice (512) 873-4700 Fax (512) 873-4900