![]() |
|
|||||||
|
|
Thread Tools | Search this Thread | Rate Thread |
|
#1
|
|||
|
|||
What's good to implement operator overloading with 'friend'?We all know how to implement operator overloading as the following:
CPP / C++ / C Code:
But sometimes I see people use friend methods: CPP / C++ / C Code:
Why do they do this way? What're the advantages? Thank you. |
|||
|
#2
|
|||
|
|||
Re: What's good to implement operator overloading with 'friend'?Quote:
Usually the data members real and imag are private to the class. The above function overloads the '+' operator for the complex class so that we can write z = x + y for complex objects. It operates on two objects of the class and the result is a member of the class. Since it is being defined as a member function of the class, it has access to all members (public and private) of the class. As you imply, this is pretty much standard stuff. Quote:
Quote:
Friend operators defined in a class will allow access to private members from other classes. Since this operates on two complex objects and gives a complex object, I'm not sure who could be a friend. Now a good reason to define a function as a friend be if you wanted to overload the '<<' operator so that an ostream object could access the private members of the complex class in order to print them out. CPP / C++ / C Code:
Regards, Dave |
|
#3
|
|||
|
|||
Re: What's good to implement operator overloading with 'friend'?hai meili, they done this prg in this way becuase...........
while u pass any arguments that are not modified in the function(the data members of an object), it is always better to send them as const objects which enables faster compilation,so they done so.... n why they use friend fun is,u want to store the result of the two complex numbers in the third complex no., the calling of the function (overloaded operator) is interpreted by the compiler in the following way........ complex1+complex2; //in compiler-> operator +(complex1,complex2); so in order to store the result in the third complex object it should return the reference to the resultant complex,n if u use class member fun, it is not possible to return the reference as the compiler under stands the call as follows complex1+complex2 //in compiler it is treated as complex1.operator +(complex2); so we need frend fun..... thats wht dave explained u..... regards surya |
Recent GIDBlog
Install Adobe Flash - Without Administrator Rights by LocalTech
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Please recommend a good, user-friendly website builder | dreambuilder | Web Design Forum | 11 | 23-Aug-2007 15:53 |
| Help with creating files in c | molatelo | C Programming Language | 1 | 28-Apr-2007 07:20 |
| friend functions error | CaptnB | C++ Forum | 2 | 12-Jun-2006 13:39 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The