今天就给大家分享一个关于C++函数重载的小问题。
首先说明,所谓重载,即是在函数名相同的情况下,而函数标识不同下实现两个或者多个函数的功能。
我们把函数名和形参列表合称为函数标识,注意函数返回值是不算在里面的。下面我们直接上出试验代码:
#include<stdio.h>
#include<iostream>
using namespace std;
class Test{
private:
int arg1;
int arg2;
public:
Test(int a,int b){
arg1=a;
arg2=b;
}
int fun(){
return arg1+arg2;
}
double fun(){
return arg1+arg2+3.1415926;
}
};
int main(){
Test test(3,1);
cout<<test.fun()<<endl;
return 0;
}
上面代码编译后会出现编译错误,如下:
14行:error:with 'int Test::fun()'即是fun()函数申明或定义时出现错误(错误会抛出在该函数首次出现的地方)
17行报出的错误具体意思为:'double Test::fun()'没能重载,即重载出现错误。
正确的代码如下:
#include<stdio.h>
#include<iostream>
using namespace std;
class Test{
private:
int arg1;
int arg2;
public:
Test(int a,int b){
arg1=a;
arg2=b;
}
int fun(){
return arg1+arg2;
}
double fun(int b){
return arg1+arg2+3.1415926;
}
};
int main(){
Test test(3,1);
cout<<test.fun(5)<<endl;
return 0;
}
最后再说一点,C++重载函数的区分是根据函数名与参数列表二者相结合而完成的,而实际在编译器中,编译器对代码进行编译之后会对函数加上标记符以作为区分处理:
例如上面两个函数经过处理过后可能变成:
int fun()@xxy;
double fun()@xxz;