函数重载中的参数const问题

1.奇怪的现像:

int get(int );
int get(const int);
//上面这样是可以的,不报错

int get(int );
double get(const int);
//error: ambiguating new declaration of 'double get(int)'
//上面这样会报错。

第一种是C++中函数可以重复声明,但不能重复定义;而第二种的意思就只有返回类型不同不能构成函数重载。

但是这样的话,如果两者都有了实现,就会报错:

int get(int a){cout<<"int a"; return a;}
int get(const int a){cout<<"const in a"; return a;}//error: redefinition of 'int get(int)'
int main(){
    const int a=5;
    get(a);
        return 0;
}   

如果将参数改为引用类型或者是指针类型,就可以了:

int get(int &a){cout<<"int a"; return a;}
int get(const int &a){cout<<"const in a"; return a;}
int main(){
    const int a=5;
    get(a);
        return 0;
}

#结果:
const in a

这样的话就会自动匹配了。

原文地址:https://www.cnblogs.com/BlueBlueSea/p/13899233.html