C + + allows functions with similar functions to be declared with the same function name within the same scope, resulting in overloading, ease of use, and ease of memory.
/* different form parameter types */ int Add (int x,int y); float Add (float x,float y); /* The number of formal parameters is different */ int Add (int x,int y); int Add (int x,int y,int z);
Precautions:
>> the parameters of an overloaded function must be different: the number is different or the type is different
The >> compiler chooses which function to invoke based on the best match of the type and number of arguments and parameters
/* The compiler does not differentiate by formal parameter names */ int Add (int x,int y); int Add (int A,int b); /* The compiler does not differentiate from the return value */ int Add (int x,int y); void Add (int x,int y);
>> do not declare functions of different functions as overloaded functions in order to avoid misunderstandings and confusion about the result of the call.
int Add (int x,intreturn x +y;} float Add (float x,floatreturn XY;}
Examples of overloaded function applications:
Write two overloaded functions named Sumofsquare, respectively, to find the sum of squares of two integers and the sum of squares of two real numbers.
#include <iostream>using namespacestd;intSumofsquare (intAintb) { returnA * a + b *b;}DoubleSumofsquare (DoubleADoubleb) { returnA * a + b *b;}intMain () {intm, N; cout<<"Enter the integer:"; CIN>> m >>N; cout<<"their sum of square:"<< Sumofsquare (M, N) <<Endl; Doublex, y; cout<<"Enter The real number:"; CIN>> x >>y; cout<<"their sum of square:"<< sumofsquare (x, y) <<Endl; System ("Pause"); return 0;}
Output Result:
c++--function overloading