一、重载的定义
重载声明是指在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。返回值的类型不同,不能作为重载函数的判断依据。
// 如下举例一组重载函数:
void fun(int a);
void fun(int a,int b);
void fun(double a,int b);
void fun(double a,double b);
void fun(const char* str);
void fun(char* str);
二、值传递作为参数,加const不构成重载
int test(const int a)
{
return a;
}
int test(int a)
{
return a;
}
int main()
{
int value = 1;
std::cout << test(value) << std::endl;
system("pause");
return 0;
}
编译出错,因为这是值传递,value只是把值传进去了,并不是把自己传进去
三、指针、引用作为参数加const构成重载
int test(const int* a)
{
return *a;
}
int test(int* a)
{
return *a;
}
int main()
{
int a = 1;
std::cout << test(&a) << std::endl;
const int b = 2;
std::cout << test(&b) << std::endl;
system("pause");
return 0;
}
编译,运行 正常。因为传入的是指针,它是引用传递,这个const是有效的,它会影响到底传进去的这个指针能不能被修改。
四、类里的成员函数加const构成重载
class MyClass
{
public:
int test()
{
m_num = 1;
return m_num;
}
int test() const
{
return 2;
}
private:
int m_num = 0;
};
int main()
{
MyClass my1;
const MyClass my2;
std::cout << my1.test() << std::endl;
std::cout << my2.test() << std::endl;
system("pause");
return 0;
}
运行
原理:
非const对象调用的是没有const修饰的函数,而const对象调用的是用const修饰的函数。
因为类的成员函数的参数中,其实还有一个隐式的this指针,它会在在调用的时候传入。
在非const修饰的函数中,this指针也是非const的。在const修饰的函数中,this指针是const修饰的。
参考:
C++类中const修饰的函数与重载_未来之大神的博客-CSDN博客
C++ 加const能不能构成重载的几种情况_learner_pu的博客-CSDN博客_变量前有无const是否可以重载