博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++函数重载(3) - 函数重载中的const关键字
阅读量:4071 次
发布时间:2019-05-25

本文共 1804 字,大约阅读时间需要 6 分钟。

目录


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

参考下面程序的输出:
#include
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
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
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类型进行函数重载。详情可参考本系列 。
这就是为何例子1编译失败,例子2正常的原因。
 

3.总结

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

转载地址:http://hmeji.baihongyu.com/

你可能感兴趣的文章
环境分支-git版本管理
查看>>
uni-app 全局变量
查看>>
js判断空对象的几种方法
查看>>
java 不用递归写tree
查看>>
springboot2 集成Hibernate JPA 用 声明式事物
查看>>
fhs-framework jetcache 缓存维护之自动清除缓存
查看>>
SpringBoot 动态编译 JAVA class 解决 jar in jar 的依赖问题
查看>>
fhs-framework springboot mybatis 解决表关联查询问题的关键方案-翻译服务
查看>>
ZUUL2 使用场景
查看>>
Spring AOP + Redis + 注解实现redis 分布式锁
查看>>
elastic-job 和springboot 集成干货
查看>>
php开发微服务注册到eureka中(使用sidecar)
查看>>
mybatis mybatis plus mybatis jpa hibernate spring data jpa比较
查看>>
支付宝生活号服务号 用户信息获取 oauth2 登录对接 springboot java
查看>>
CodeForces #196(Div. 2) 337D Book of Evil (树形dp)
查看>>
uva 12260 - Free Goodies (dp,贪心 | 好题)
查看>>
uva-1427 Parade (单调队列优化dp)
查看>>
【设计模式】学习笔记13:组合模式(Composite)
查看>>
hdu 1011 Starship Troopers (树形背包dp)
查看>>
hdu 1561 The more, The Better (树形背包dp)
查看>>