Question:
about operator overloading?
gagan
2007-10-10 04:55:39 UTC
can anybody pls give me the coding for the operator overloading of assignment operator,address operator ,stream insertion and stream extraction operators???????????
thnks
Three answers:
Rahul Ghose
2007-10-11 11:45:15 UTC
Say for a class String I am overloading the operator += to add to the string (append) an object of that class and a normal string.

My definitions would go:

String operator+=(String&);

String operator+=(const char*);

And the code would be:



String String::operator+=(String &other) /* adds another object*/

{

data = (char *)realloc(data,(strlen(data)+strlen(other.data))*sizeof(char)+1);

return strcat(data,other.data);

}



String String::operator+=(const char* other)

{

data = (char *)realloc(data,(strlen(data)+strlen(other))*sizeof(char)+1);

return strcat(data,other);

}



Examine these codes.



Now for iostreams:

The declarations:

friend ostream& operator << ( ostream&, String& ) ;

friend istream& operator >> ( istream&, String& ) ;

The corresponding codes:



ostream& operator << ( ostream &strm, String &x )

{

strm<
return strm ;

}



// friend function to input objects of string class

istream& operator >> ( istream &strm, String &x )

{

char *buffer ;

buffer = new char[256] ;



if ( strm.get( buffer, 255 ) )

x = String ( buffer ) ;



return strm ;

}
shilpa
2007-10-10 08:39:22 UTC
check out in any of the text books u il surely get it.

Cant write d whole assignment for u
Sandy
2007-10-10 05:07:10 UTC
you need to first tell in which language do you want the code


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...