function overloading in c++

     Function polymorphism is also known as function overloading.

 (1) Function overloading means that there can be multiple functions with the same name, so the names are overloaded.

 (2) The key to function overloading is the parameter list of the function, also known as the function signature. If two functions have the same number and type of parameters, and the parameters are in the same order, then their signatures are the same, and the variable names are irrelevant.

    (3) C++ allows functions with the same name to be defined, provided that their signatures are the same. If the number of arguments and/or the types of arguments are different for the two functions, the signatures are also different.

    (4) The signature of the standard function that c++ judges whether to overload.

    (5) If only the return value types of the functions are different, but the signatures of the functions are the same, it cannot be considered as overloading. (Sometimes we don't need to return a value, so the editor can't see which function was called)

    Demo_01:

#include <iostream>
unsigned long left (unsigned long num, unsigned int ct);
char * left (const char *str, int n = 1);
intmain()
{
	using namespace std;
	char *trip = "HelloWorld";
	unsigned long n =  12345;
	char *temp;
	for (int i = 1; i < 11; i++)
	{
		cout << left(n, i) << endl;
		temp = left(trip, i);
		cout <<temp<<endl;
		delete [] temp;
	}
	return 0;
}

unsigned long left(unsigned long num, unsigned int ct)
{
	unsigned digits = 1;
	unsigned long n = num;

	if (ct == 0 || num == 0)
	{
		return 0;
	}
	while (n /=10)
	{
		digits++;
	}
	if (digits > ct)
	{
		ct = digits - ct ;
		while (ct--)
		{
			num /= 10;
		}
		return num;
	}
	else
	{
		return num;
	}
}

char * left(const char *str, int n /*= 1*/)
{
	if (n < 0)
	{
		n = 0;
	}
	char *p = new char[n+1];
	int i, count;
	for (i = 0; i < n && str[i]; i++)
	{
		p[i] = str[i];
	}
	while (i <=  n)
	{
		p[i++] = '\0';
	}
	return p;
}

 operation result:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325361903&siteId=291194637