#---------------------------------------- 函数重载-------------------------------------------
void func()
{
cout<<"func()调用"<<endl;
}
//------------参数---------------
void func(int a)
{
cout<<"func(int a)调用"<<endl;
}
//------------参数类型------------
void func(double a)
{
cout<<"func(double a)调用"<<endl;
}
//------------参数个数-------------
void func(int a,double b)
{
cout<<"func(int a,double b)调用"<<endl;
}
//------------参数顺序--------------
void func(double a,int b)
{
cout<<"func(double a,int b)调用"<<endl;
}
满足函数重载条件:
1.作用域必须相同
列如下面的func是成员函数 但不能作为重载条件
class PerSon
{
void func(){};//作用域不同
}
2.函数名称相同
3.函数的参数、类型不同、或个数不同或者顺序不同
4.返回值不可以作为函数重载的条件(原因出现二义性)
void func(double a,int b)
{
cout<<"func(double a,int b)调用"<<endl;
}
//返回类型void int不同,但编译器无法判断该使用哪一个函数
int func(double a,int b)
{
cout<<"func(double a,int b)调用"<<endl;
}
5.引用重载版本 对于引用而言,加const和不加const也可以作为重载条件
void myfunc(int & a)
{
cout<<"myfunc(int & a)调用"<<endl
}
-----------------不加const------------------
void myfunc(const int & a)
{
cout<<"myfunc(const int & a)调用"<<endl
}
-------------------加const--------------------
void test02()
{
int a=10; //a 可读可写 调用void myfunc(int & a);
myfunc(10); // 可读不可写 调用void myfunc(const int & a)
}
5.2二义性
void myfunc(int a){};//可以同时调用,应注意避免二义性
------加上引用和不加引用------------
void myfunc(int & a){};//可以同时调用,应注意避免二义性
6.函数重载遇到函数的默认参数
void myfunc2(int a,int b)
{
}
void myfunc2(int a)
{
}
void tese05()
{
myfunc2(10); //注意避免二义性
}