C++ notes-function overload (function overload)

C++ notes-function overload (function overload)

concept:

There can be n functions with the same name in the same code

  1. Function: The
    same interface has different forms of expression, realizing the unification of the interface
  2. Principle:
    When the compiler compiles the program, it will automatically replace the function with the corresponding version overloaded form
  3. Features:
  • Function overloading does not care about the return value type, the return value type is different, and everything else is the same (function name, parameter number type), it is not called function overloading
  • Function overload, function name must be the same
  • Function overloading, at least one of the number or type of parameters must be different

example

int add(int a,int b)
double  add(int a,int b) //不是重载,不关心返回值类型
void add(int a,int b);     //不是重载,不关心返回值类型
int add(int c,int d)       不是重载
int myadd(int a,int b)   //不是重载,名字不同
double add(double a,int b)  //是重载
double add(int a,double b)  //是重载 
double add(double a,double b)
double add(double a,double b,double c);   //是重载,个数不同
int add(int a,int b)
{
    
    
	cout<<"第一个版本的add"<<endl;
	return a+b;
}

double add(double a,double b)
{
    
    
	cout<<"第二个版本的add"<<endl;
	return a+b;
}

int main()
{
    
    
	int a=78;
	int b=74;
	double c=45.6;
	double d=52.3;
	float e=85.6;
	//编译器根据实参的类型和个数匹配对应版本的add
	cout<<add(a,b)<<endl; //编译器把这个翻译成  add(int,int)
	cout<<add(c,d)<<endl; //编译器把这个翻译成  add(double,double)
	
	//cout<<add(a,e)<<endl;  //错误,类型不匹配
	//cout<<add(a,b,c)<<endl; //错误,类型和个数都不匹配
}

C++ function overloading does not care about the return value type

#include <iostream>
using namespace std;

int add(int a,int b)
{
    
    
	cout<<"第一个版本的add"<<endl;
	return a+b;
}



double add(double a,double b)
{
    
    
	cout<<"第二个版本的add"<<endl;
	return a+b;
}


double add(int a,int b)
{
    
    
	cout<<"第三个版本的add"<<endl;
	return a+b;
}
int main()
{
    
    
	int a=78;
	int b=74;
	double c=45.6;
	double d=52.3;
	float e=85.6;
		
	//编译器根据实参的类型和个数匹配对应版本的add
	cout<<add(a,b)<<endl; //编译器把这个翻译成  add(int,int)
	cout<<add(c,d)<<endl; //编译器把这个翻译成  add(double,double)
	
	//cout<<add(a,e)<<endl;  //错误,类型不匹配
	//cout<<add(a,b,c)<<endl; //错误,类型和个数都不匹配
}

Guess you like

Origin blog.csdn.net/weixin_46026429/article/details/108507885