Mega Code Archive

 
Categories / C++ / Class
 

Define friend function for

#include <iostream> #include <cstring> #include <cstdlib> using namespace std; class StringClass {   char *p;   int len; public:   StringClass(char *ptr);   ~StringClass() {      delete [] p;   }   friend ostream &operator<<(ostream &stream, StringClass &ob); }; StringClass::StringClass(char *ptr) {   len = strlen(ptr)+1;   p = new char [len];   if(!p) {     cout << "Allocation error\n";     exit(1);   }   strcpy(p, ptr); } ostream &operator<<(ostream &stream, StringClass &ob) {   stream << ob.p;      return stream; } int main() {   StringClass stringObject1("www.rntsoft.com"), stringObject2("www.rntsoft.com");   cout << stringObject1;   cout << endl << stringObject2 << endl;   return 0; }