Function Overloading. McGraw-Hill The Complete Reference Fourth Edition
Oglas
Oglas
360
C + + : T h e C o m p l e t e R e f e r e n c e
T his chapter examines function overloading, copy constructors, and default arguments. Function overloading is one of the defining aspects of the C++ programming language. Not only does it provide support for compile-time polymorphism, it also adds flexibility and convenience. Some of the most commonly overloaded functions are constructors. Perhaps the most important form of an overloaded constructor is the copy constructor. Closely related to function overloading are default arguments. Default arguments can sometimes provide an alternative to function overloading.
Function Overloading
Function overloading is the process of using the same name for two or more functions.
The secret to overloading is that each redefinition of the function must use either different types of parameters or a different number of parameters. It is only through these differences that the compiler knows which function to call in any given situation.
For example, this program overloads myfunc( ) by using different types of parameters.
#include <iostream> using namespace std; int myfunc(int i); // these differ in types of parameters double myfunc(double i); int main()
{ cout << myfunc(10) << " "; // calls myfunc(int i) cout << myfunc(5.4); // calls myfunc(double i)
} return 0; double myfunc(double i)
{ return i;
} int myfunc(int i)
{ return i;
}
C h a p t e r 1 4 : F u n c t i o n O v e r l o a d i n g , C o p y C o n s t r u c t o r s , a n d D e f a u l t A r g u m e n t s
361
The next program overloads myfunc( ) using a different number of parameters:
#include <iostream> using namespace std; int myfunc(int i); // these differ in number of parameters int myfunc(int i, int j); int main()
{ cout << myfunc(10) << " "; // calls myfunc(int i) cout << myfunc(4, 5); // calls myfunc(int i, int j)
} return 0; int myfunc(int i)
{ return i;
} int myfunc(int i, int j)
{ return i*j;
}
As mentioned, the key point about function overloading is that the functions must differ in regard to the types and/or number of parameters. Two functions differing only in their return types cannot be overloaded. For example, this is an invalid attempt to overload myfunc( ): int myfunc(int i); // Error: differing return types are float myfunc(int i); // insufficient when overloading.
Sometimes, two function declarations will appear to differ, when in fact they do not.
For example, consider the following declarations.
void f(int *p); void f(int p[]); // error, *p is same as p[]
Remember, to the compiler *p is the same as p[ ]. Therefore, although the two prototypes appear to differ in the types of their parameter, in actuality they do not.
Preuzimanje
Oglas