C++类中const修饰的函数与重载

一、重载的定义

重载声明是指在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。返回值的类型不同,不能作为重载函数的判断依据。

// 如下举例一组重载函数:
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++ 重载运算符和重载函数 | 菜鸟教程

C++类中const修饰的函数与重载_未来之大神的博客-CSDN博客

C++ 加const能不能构成重载的几种情况_learner_pu的博客-CSDN博客_变量前有无const是否可以重载

  • 8
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值