c++ const成员函数

const 成员函数中

  • const成员函数可以访问非const对象的非const数据成员,const数据成员,也可以访问const对象内的所有数据成员;
  • 非const成员函数只可以访问非const对象的任意的数据成员(不能访问const对象的任意数据成员)
  • 如果只有const成员函数,非const对象是可以调用const成员函数的。当const版本和非const版本的成员函数同时出现时,非const对象调用非const成员

举例子

class MyClass
{
public:
    int x,y;
    MyClass();
    MyClass(int x,int y);
    ~MyClass();
    void fun()
    {
        cout<<"non const"<<endl;
    
    }
    void fun() const
    {
        cout<<"const"<<endl;
    
    }
private:

};

MyClass::MyClass()
{
}
MyClass::MyClass(int x,int y)
{
    this->x = x;
    this->y = y;
}



MyClass::~MyClass()
{
}


int _tmain(int argc, _TCHAR* argv[])
{
    MyClass c1;
    c1.fun();
    const MyClass c2;
    c2.fun();
    MyClass * const d = &c1; //指针常量 不改变指向 可改变指向的数据
    d->fun();
    MyClass  const *e = &c2; //常量指针 指向常量对象的指针,不能改变数据,可以改变指向。
    e->fun();
    
    return 0;
}

const和非const成员函数同时存在时,普通对象优先调用非 const成员函数

const对象不能调用非const成员函数

const成员函数隐藏了this指针,本质上是对成员变量加const,即不能通过const成员函数改变成员变量的值。

举例

class MyClass
{
public:
    int x,y;
    MyClass();
    MyClass(int x,int y);
    ~MyClass();
    void fun()
    {
        cout<<"non const"<<endl;
    
    }
    void fun() const
    {
        x = 5;  //此处提示错误 表达式必须是可修改的左值。
        cout<<"const"<<endl;
    
    }
private:

};

参考博客:https://www.cnblogs.com/cthon/p/9178701.html

原文地址:https://www.cnblogs.com/9527s/p/13130131.html