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

C++类中const修饰的函数与重载

2016-09-19 22:45 357 查看
const修饰常量比较好理解,const修饰函数可能会有点生疏。

const修饰的函数,不能修改类中的成员变量,这是const修饰函数的基本作用。

const修饰的函数同时也能实现函数的重载。

函数的重载主要是指函数名相同,返回类型相同,参数列表相同。

那么何为const修饰函数实现函数重载呢。

实际上就是说,类中已经有一个方法,我们再给这个类加一个一模一样的方法,但是这个方法是用const修饰,从而实现了重载。

有两个问题:

1.参数列表一样为什么能实现重载?

2.在调用这个函数的时候到底会调用哪一个呢?

用代码实现一下这个重载。

class Test

{

public:
Test();
~Test();
int num;
int fun();
int fun(int b) const;
int fun(int b);

};

Test::Test()

{
cout << "Test()" << endl;

}

Test::~Test()

{

}

int Test::fun()

{
cout << " int fun();" << endl;
return 0;

}

int Test::fun(int b)

{
cout << " int fun(int b);" << endl;
num = 2;
return 0;

}

int Test::fun(int b) const

{
cout << " int fun(int b) const;" << endl;
return 0;

}

int main()

{
Test test;
const Test testC;
test.fun();
test.fun(3);
testC.fun(3);
system("pause");
return 0;

}

代码的输出为:

Test()

Test()

 int fun();

 int fun(int b);

 int fun(int b) const;

分析:

1.程序编译通过了,重载的功能也能实现。

2.非const对象调用的是没有const修饰的函数,而const对象调用的是用const修饰的函数。

3.经查资料,这些函数的参数中其实还有一个隐式的this指针,在调用的时候传入。

因为在非const修饰的函数中,this指针也是非const的。在const修饰的函数中,this指针是const修饰的。

所以非const对象调用函数时,this指针是非const的,调用非const函数。const对象调用函数时,this指针是const的,调用的是const的函数。

4.有了参数上的非const与const的不同,所以const修饰函数能实现函数的重载。

结论:

const修饰的函数不仅能限制函数去修改成员变量,同时也能实现函数的重载。要想调用const修饰的重载函数,需要用const对象去调用。

另外要注意的是,如果一个函数用const修饰了,但是这个函数没有实现重载,那么非const对象和const对象都能调用这个函数。

特别注意的是,const修饰的对象只能调用const修饰的函数,比如,testC.fun()是错误的,因为fun()是非const的,而testC是const的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: