18.3 Operator Member Functions

I l @ ve RuBoard

So far we've been using operator overloading functions just like ordinary functions. They can also be defined as member functions. The only difference is that as member functions the first argument, the class itself, is implied . For example, you can write the operator += as an ordinary function or as a member function. Here's the ordinary version that you've already seen:

 inline fixed_pt& operator +=(fixed_pt& oper1, const fixed_pt& oper2)  {     oper1.value += oper2.value;     return (oper1); } 

Here's the member function:

 class fixed_pt {     // .....     public:         inline fixed_pt& operator +=(const fixed_pt& oper2)          {             value += oper2.value;             return (*this);         } 

The only trick used in this function is the keyword this . This is a predefined variable that refers to the current object. For example, you can access the data member value using the statement:

 value += oper2.value; 

The same statement can be written as:

 this->value += oper2.value; 

In most cases, you don't need to use this . In a few cases, however, such as with the += operator, it comes in handy.

Which flavor of the operator overloading functions should you use? The one that makes your program the clearest and easiest to read. In general, I use the standard functions for the simple operators, such as +, -, *, and /, while I use member functions for the shortcut and unary operators, such as +=, -=, ++, and unary -.

Some overloaded functions work only as member functions. These include the casting operators and class-specific versions of new and delete .

All overload operator functions that have the class type as the left argument should be member functions. This helps keep everything in one well-designed class.

18.3.1 Casting

Finally we come to the cast operators. Casting is a way of changing one type to another, such as when we cast our fixed_pt type to a long int (truncating the two digits after the decimal point). We can define a cast operator for this function as:

 class fixed_pt {     public:         // (We didn't really put this in our fixed_point class)          operator double(  ) {return (value / fixed_exp);} 

C++ automatically calls this function whenever it wants to turn a fixed_pt into a long int.

The trouble is that by defining a cast, you give C++ something else that it can call behind your back. Personally, I like to know whenever C++ calls something, so I avoid creating cast operators. Unless you have a very good reason to define one, don't create a cast operator function.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net