const函数重载

C++允许类的成员函数基于const重载。

#include<iostream>
using namespace std;
 
class Test
{
protected:
    int x;
public:
    Test (int i):x(i) { }
    void fun() const
    {
        cout << "fun() const called " << endl;
    }
    void fun()
    {
        cout << "fun() called " << endl;
    }
};
 
int main()
{
    Test t1 (10);
    const Test t2 (20);
    t1.fun();
    t2.fun();
    return 0;
}

输出:

fun() called
fun() const called
我们可以看到非const对象调用的是非const成员函数,const对象调用的是const成员函数。

下面两个例子很有意思,重载不是类的成员函数,而是普通函数的重载,

程序1

#include<iostream>
using namespace std;
 
void fun(const int i)
{
    cout << "fun(const int) called ";
}
void fun(int i)
{
    cout << "fun(int ) called " ;
}
int main()
{
    const int i = 10;
    fun(i);
    return 0;
}

输出:

编译错误!

error C2084: 函数“void fun(const int)”已有主体

error C3861: “fun”: 找不到标识符


程序2

#include<iostream>
using namespace std;
 
void fun(char *a)
{
  cout << "non-const fun() " << a;
}
 
void fun(const char *a)
{
  cout << "const fun() " << a;
}
 
int main()
{
  const char *ptr = "CSDN";
  fun(ptr);
  return 0;
}

输出:

const fun()  CSDN


这里程序1会出现编译通不过,而程序2能正确运行,为什么?因为C++只有当参数是指针或引用时才允许非成员函数const重载。实际上很好理解,在程序1中,i是值传替,fun中的参数i的值是main中的i的一份拷贝,因此对于是否接受的是const还是non-const参数没有关系,它并不能改变main中的i的值。但是,当我们使用引用或者指针的时候,我们就能修改main中的i的值。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值