C++函数重载(3) - 函数重载中的const关键字

目录

1.const可用于重载成员函数

2.参数处理

3.总结


1.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

这两个成员函数‘void fun() const’和‘void fun()’有着相同的函数名,返回值以及参数列表,只是一个带有const另一个没有。
另外,如果仔细观察下输出,会发现 ‘const void fun()’函数是由一个const对象调用的,而‘void fun()’函数是由一个非const对象调用。
C++允许成员方法基于基本的const类型来进行重载。基于const类型的重载,在函数返回引用或指针的情况下是有用的。我们可以构造一个const函数,然后返回一个const引用或const指针;或者构造一个非const函数,返回非const引用或指针。

2.参数处理

与const参数相关的规则很有趣。首先看看下面的两个例子。例子1会编译失败,例子2运行正常。
//例子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;
}

输出:
Compiler Error: redefinition of 'void fun(int)'

//例子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 = "hello world";
  fun(ptr);
  return 0;
}

输出:
const fun() hello world

仅当const参数是一个引用或指针时,C++才允许基于const类型进行函数重载。详情可参考本系列 第2篇
这就是为何例子1编译失败,例子2正常的原因。
 

3.总结

这条规则是有意义的。本例子中,参数i按值传递,所以fun()中的i是main()中的i的一个拷贝。因此fun()无法修改main()中的i。因此,无论i是做为一个const参数或正常参数,都没有什么区别。
如果是按引用或指针传递,则我们可以修改引用或指针所代表的对象的值,因此,这两个函数相当于实现了不同的版本。其中一个可以修改引用或指针的值,另一个不能。
 
做为验证,参考下面的另一个例子。
#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;
}

输出:
fun(const int &) called 
 

  • 13
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值