Expert C Programming

(Jeff_L) #1

class Fruit { public: void peel(); slice(); juice();


int operator+(Fruit &f); // overload "+"


operator


private: int weight, calories_per_oz;


} ;


Then provide a body for the overloaded operator function:


int Fruit::operator+(Fruit &f) {


printf("calling fruit addition\n"); // just so we


can see


return weight + f.weight;


}


As before, every method is passed an implicit this pointer, allowing us to reference the left operand
of the operator. The right operand of the addition is the parameter called f here; it is an instance of
Fruit, and the preceding ampersand indicates it is passed by reference.


The overloaded function can be called like this:


Apple apple;


Fruit orange;


int ounces = apple+orange;


The precedence and number of operands ("arity" in compiler jargon) remain the same for the
overloaded operator as for the original operator. So, you see, C++ says you can add apples to oranges,
if you define it first. C++ gives the phrase "operator error" a whole new class of meanings.
Overloading is also very convenient in C++ I/O, described in the next section.


Input/Output in C++


As well as having the stdio library of C, C++ features some new I/O routines and concepts of its own.
There is an I/O interface known as iostream.h that helps to make I/O more convenient [3] and more
in tune with the object-oriented philosophy.


[3] Don't confuse the C++ iostream (formerly known as streams) I/O interface with the


unrelated UNIX kernel STREAMS framework for communicating between a device driver and a
user process.


The operators << (to put, or "insert") and >> (to get, or "extract") are used instead of functions like
putchar() and getchar().

Free download pdf