C++中的函数重载
时间:2020-02-23 14:29:58 来源:igfitidea点击:
什么是函数重载?
C++编程语言为其用户提供了非常有用的功能,即函数重载。
它允许用户为两个或者多个函数使用相同的名称,并使用不同数量或者类型的参数。
例如,
int demo(int); int demo(int, int); int demo(float);
其中我们使用相同的函数名称" demo"来声明三个不同的函数。
请注意,它们全部采用不同数量或者类型的参数。
因此,所有这些函数都可以在单个程序中使用,并且函数调用将完全取决于传递的参数的类型和数量。
例如,如果将以下函数(尽管返回类型不同)与上述函数一起使用,则会引发错误。
float demo(int)
这是因为它采用与先前声明的第一个函数相同的参数类型和数量。
示例–使用C++中的函数重载计算周长
现在,让我们看一个简单的示例,在该示例中,我们通过在C++中实现函数重载概念,尝试根据用户的选择来计算正方形/三角形/矩形的周长。
#include<iostream>
using namespace std;
float peri(float x)
{
return 4*x;
}
float peri(float a, float b, float c)
{
return (a+b+c);
}
float peri(float l, float b)
{
return 2*(l+b);
}
int main()
{
float x, y, z;
int ch;
cout<<"::: Menu for calculating perimeter :::"<<endl;
cout<<"1. Square"<<endl;
cout<<"2. Triangle"<<endl;
cout<<"3. Rectangle"<<endl;
cout<<"Enter your choice(1/2/3) : ";
cin>>ch;
switch(ch)
{
case 1: cout<<"\n\nEnter edge for the Square: ";
cin>>x;
cout<<"\nPerimeter = "<<peri(x)<<" units";
break;
case 2: cout<<"\n\nEnter 1st side length: ";
cin>>x;
cout<<"\nEnter 2nd side length: ";
cin>>y;
cout<<"\nEnter 3rd side length: ";
cin>>z;
cout<<"\nPerimeter = "<<peri(x,y,z)<<" units";
break;
case 3: cout<<"\n\nEnter length for the Rectangle: ";
cin>>x;
cout<<"\nEnter breadth for the Rectangle: ";
cin>>y;
cout<<"\nPerimeter = "<<peri(x,y)<<" units";
break;
default: cout<<"Wrong Choice!";
exit(0);
}
return 0;
}
其中我们使用switch结构来计算正方形,三角形或者矩形中任何一个的周长。
用户可以选择" ch"来确定要进行数据输入的形状。
在用户在"switch"中做出选择之后,我们获取不同形状的数据,并将其传递给" peri()"函数,以打印相应的周长。
在这种情况下,对" peri()"的函数调用完全取决于传递给它的参数数量。
因此,对于单个参数,编译器会自动调用第一个函数并返回一个正方形的周长。
因此,对于两个参数和三个参数,分别调用计算矩形和三角形周长的相应函数。

