Friend functions are functions defined outside a class (ie, not member functions), but which the class declares to be friends so that they can use the class's private members. This is commonly used in operator overloading.
Overloading input/output operators
Perhaps the most common use of friend functions is overloading << and >> for I/O. See Overloading << and >>.
Commutative operators
Another use of friend functions is to permit operators to be commutative. An operator is commutative if the result is the same regardless of the order of its operands. Some typical examples are addition and multiplication. Subtraction and division are not commutative.
Assuming x is an object of a class you've written and i is an integer, x+i should have the same meaning as i+x. The + in x+i is ok if the + operator between an object and an int is defined as a member function in x's class. However the + in the second case (i+x) can only be written as a friend function. That's because overloading (redefining) operators can only be done for classes, not the primitive types, and the operator definition that is used is based on the class of the left operand.
Declare friends before public and private
A class doesn't control the scope of friend functions so friend function declarations are usually written at the beginning of a .h file. Public and private don't apply to them.
Wednesday, August 19, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment