[C++] function overloading

[C++] function overloading

        In the c language, each function must have a unique name, so the name of each function must be remembered. For example: functions for finding areas, circles, rectangles, and trapezoids must each have a separate function. In C++, multiple functions with the same name are allowed to exist, that is, function overloading. The requirement of function overloading is that the parameters of each function are different: the number of parameters is not the same, or the parameter types are not the same.

         Note: 1. Function overloading is achieved by distinguishing the number and type of parameters, regardless of the return value.

                    2. The overloaded function cannot have the same name as the function with the default value, otherwise the system cannot determine which one to call.

                    {

                        void point(int a,int b);

                        void point(int a,int b=2,int c=3);

                        point(x,y); //will not know which one to call

                    }


 Code:

        For example: find a function of area. Although they are all functions of finding area, they can be distinguished by the number of parameters.

// function overloading

#include<iostream>

using namespace std;

double area(double r);  //圆
double area(double w,double h); //矩形
double area(double a,double b,double h); //梯形
 
intmain()
{
	double r=5;
	double s1;
	s1=area(r);
	cout<<"Area of ​​the circle:"<<s1<<endl;
	
	double w=2,h=5;
	s1=area(w,h);
	cout<<"The area of ​​the rectangle:"<<s1<<endl;
	
	
	double a=3,b=5,h1=10;
	s1=area(a,b,h1);
	cout<<"The area of ​​the trapezoid:"<<s1<<endl;
	
	return 0;
}

double area(double r)
{
	double s=3.13*r*r;
	return s;

}
double area(double w,double h)
{
	double s=w*h;
	return s;

}

double area(double a,double b,double h)
{
	double s=(a+b)*h/2;
	return s;
}

operation result:

        


 -------------------------------------------         END      -------------------------------------

Guess you like

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