您的位置:首页 > 编程语言 > C语言/C++

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: