How to overload << operator?


To print the data members of an object along with a proper heading calls for writing considerable code. This can be made more efficient by overloading the extraction operator (<<). Following code shows how to overload the << operator:

#include <iostream.h>

#include <string.h>

class emp

{

private :

char name[25] ;

int age ;

char phone[15] ;

public:

emp ( char *n, int a, char *p )

{

strcpy ( name, n ) ;

age = a ;

strcpy ( phone, p ) ;

}

friend ostream& operator << ( ostream &cout, emp e ) ;

} ;

ostream& operator << ( ostream &cout, emp e )

{

cout << “\nName : ” << e.name << “\tAge : ” << e.age << “\tPhone : ” << e.phone ;

}

main( )

{

emp e1 ( “Prakash”, 24, “911-65289″ ) ;

cout << e1 ;

}

Subscribe / Share

It's very calm over here, why not leave a comment?

Leave a Reply




Categories

Powered by Yahoo! Answers