在c++中提供了对函数重载的支持,使得人们在编程时可以对不同的功能赋予相同的函数名,编译器根据(实参的类型和个数)来确定具体使用哪一个具体函数。
1 2函数重载:两个以上的函数,具有相同的函数名,但形参个数或类型不同,编译器根据形参的最佳匹配,自动确定调用的函数。
以add为例:
如果没有函数重载则对于实现加法功能的函数我们需要定义多个不同函数(整数,浮点数):
#include<iostream>
using namespace std;
int addint(int a,int b)
{
return a+b;
}
double adddouble(double a,double b)
{
return a+b;
}
int main()
{
int a,b;
double c,d;
cin>>a>>b>>c>>d
cout<<addint(a,b)<<" "<<adddouble(c,d);
return 0;
}
在调用时我们必须先确定参数类型才能选择函数,这样对调用带来极大地不便
但是对函数重载后,我们就不用先确定对应的函数:
#include<iostream>
using namespace std;
int add(int a,int b)
{
return a+b;
}
double add(double a,double b)
{
return a+b;
}
int main()
{
int a;
double b;
cin>>a>>b;
cout<<add(a,a)<<" "<<add(b,b);
return 0;
}
这样在未知参数类型时也可以使用函数,编译器会自动找到对应的函数。
2 函数重载的注意点:
重载函数的形参(个数,类型)必须不同
如果函数名相同,形参类型也相同(无论返回值是否相同),都会出现语法错误(函数重定义)
如下列常见错误
int add(int a,int b)
int add(int x,int y)//编译器不以形参名区分函数
int add(int a,int b)
void add(int a,int b)//编译器不以返回值区分函数
同时使用带有默认的形参值的函数重载形式时,要注意二义性如:
void f(int a,int b=2,int c=3);
void f(int a);
当使用f(1) 时编译器无法确定执行哪一个重载函数、
3 函数重载的一个实例
定义一个圆形类Cirlce和矩形类Rectangl
再定义一个求面积的工具类Area,该类有两个重载函数calArea可以分别用于求圆形对象的面积和矩形对象的面积
#include <iostream>
#include <string>
#include <cmath> // 包含数学常数,如pi
using namespace std;
class Circle {
public:
Circle(double rs) : r(rs) {}
double getRadius() const { return r; } // 添加getter方法
private:
double r;
};
class Rectangle {
public:
Rectangle(double hs, double ws) : h(hs), w(ws) {}
double getHeight() const { return h; } // 添加getter方法
double getWidth() const { return w; } // 添加getter方法
private:
double h, w;
};
class Area {
public:
static double calArea(const Circle& p) // 通过引用传递对象,并添加static关键字
{
return p.getRadius() * p.getRadius() * 3.14159265;
}
static double calArea(const Rectangle& p) // 通过引用传递对象,并添加static关键字
{
return p.getHeight() * p.getWidth();
}
};
int main(){
double r,h,w;
cin>>r>>h>>w;
const Circle c1(r);
Circle c2(r+2);
const Rectangle r1(h,w);
Rectangle r2(h+2,w+2);
cout<<Area::calArea(c1)<<endl;
cout<<Area::calArea(c2)<<endl;
cout<<Area::calArea(r1)<<endl;
cout<<Area::calArea(r2)<<endl;
return 0;
}