C++函数重载(3) - 函数重载中的const关键字
2015-05-24 00:50
309 查看
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引用或指针。
参数处理
与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正常的原因。
这条规则是有意义的。本例子中,参数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
相关文章推荐
- 使用const关键字进行函数重载
- 使用const关键字进行函数重载
- 关键字:Const,Const函数,Const变量,函数后面的Const
- C++ 学习之函数重载、基于const的重载
- C++成员函数末尾const关键字的作用
- 【转载】关键字:Const,Const函数,Const变量,函数后面的Const!~
- const&volatile 与函数重载
- c++ primer笔记 将关键字 const 加在形参表之后,就可以将成员函数声明为常量:
- 类的const和非const成员函数的重载
- C++函数后面加const关键字
- 4.C++中的函数重载,C++调用C代码,new/delete关键字,namespace(命名空间)
- 含有const关键字成员函数
- 函数重载之const
- C++中const成员函数和非const成员函数的重载
- 位运算+引用+const+new/delete+内联函数、函数重载、函数缺省参数
- 类的const和非const成员函数的重载
- const关键字在类的成员函数上的应用(1)
- PHP定义常量时const关键字和define()函数的区别
- 经典问题解析(1)---const和引用、指针与引用、函数重载、C方式编译
- 函数中关于const关键字使用的注意事项