Mega Code Archive

 
Categories / C++ Tutorial / Operator Overloading
 

Ostream and istream operator for a class

#include <iostream> #include <cstring> using namespace std; class MyClass {   char name[80];   int id;   int prefix;   int value; public:   MyClass() { };   MyClass(char *n, int a, int p, int nm)   {     strcpy(name, n);     id = a;     prefix = p;     value = nm;   }   friend ostream &operator<<(ostream &stream, MyClass o);   friend istream &operator>>(istream &stream, MyClass &o); }; // Display name and phone valueber. ostream &operator<<(ostream &stream, MyClass o) {   stream << o.name << " ";   stream << "(" << o.id << ") ";   stream << o.prefix << "-" << o.value << "\n";   return stream; // must return stream } // Input name and telephone valueber. istream &operator>>(istream &stream, MyClass &o) {   cout << "Enter name: ";   stream >> o.name;   cout << "Enter id: ";   stream >> o.id;   cout << "Enter prefix: ";   stream >> o.prefix;   cout << "Enter value: ";   stream >> o.value;   cout << "\n";   return stream; } int main() {   MyClass a;   cin >> a;   cout << a;   return 0; } Enter name: Joe Enter id: 123 Enter prefix: 1 Enter value: 2 Joe (123) 1-2