|
|
 |
|
|
|
|
50:
51: // Driver program to demonstrate overloaded functions
52: int main()
53: {
54: // initialize a rectangle to 30,5
55: Rectangle theRect(30,5);
56: cout << DrawShape(): \n;
57: theRect.DrawShape();
58: cout << \nDrawShape(40,2): \n;
59: theRect.DrawShape(40,2);
60: return 0;
61: } |
|
|
|
|
|
|
|
|
DrawShape():
******************************
******************************
******************************
******************************
****************************** |
|
|
|
|
|
|
|
|
DrawShape(40,2):
****************************************
**************************************** |
|
|
|
|
|
|
|
|
This listing passes width and height values to several functions. You should note that sometimes width is passed first and, at other times, height is passed first. |
|
|
|
|
|
|
|
|
|
Analysis: The important code in this listing is on lines 13 and 14, where DrawShape() is overloaded. The implementation for these overloaded class methods is on lines 2949. Note that the version of DrawShape() that takes no parameters simply calls the version that takes two parameters, passing in the current member variables. Try very hard to avoid duplicating code in two functions. Otherwise, when you make changes to one or the other, keeping the two of them in synch will be difficult and error-prone. |
|
|
|
|
|
|
|
|
The driver program, on lines 5261, creates a Rectangle object and then calls DrawShape(), first passing in no parameters and then passing in two integers. |
|
|
|
|
|
|
|
|
The compiler decides which method to call based on the number and type of parameters entered. You can imagine a third overloaded function named DrawShape() that takes one dimension and an enumeration for whether it is the width or height, at the user's choice. |
|
|
|
|
|