const函数重载

来源:互联网 发布:kindle 购买 知乎 编辑:程序博客网 时间:2024/05/21 17:12

C++允许类的成员函数基于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() calledfun() const called
我们可以看到非const对象调用的是非const成员函数,const对象调用的是const成员函数。

下面两个例子很有意思,重载不是类的成员函数,而是普通函数的重载,

程序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;}

输出:

编译错误!

error C2084: 函数“void fun(const int)”已有主体

error C3861: “fun”: 找不到标识符


程序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 = "CSDN";  fun(ptr);  return 0;}

输出:

const fun()  CSDN


这里程序1会出现编译通不过,而程序2能正确运行,为什么?因为C++只有当参数是指针或引用时才允许非成员函数const重载。实际上很好理解,在程序1中,i是值传替,fun中的参数i的值是main中的i的一份拷贝,因此对于是否接受的是const还是non-const参数没有关系,它并不能改变main中的i的值。但是,当我们使用引用或者指针的时候,我们就能修改main中的i的值。
0 0