c++ const 成员函数

const 成员函数: (1)、不允许修改成员变量;

        (2)、mutable修饰符的成员变量,对于任何情况下通过任何手段都可修改,自然此时的const成员函数是可以修改它的;

        (3)、不允许访问非const函数。

class Demo
{
public:
    void print() const; //常成员函数
    int get() const;
    void set();
private:
    int m_int;    
    mutable int m_mut;
};

void Demo::print() const
{
    m_int = 0;//error,(1)
    set(); //error (2)
    get(); //ok
    m_mut = 20;//ok

  

const对象只能访问const成员函数,而非const对象可以访问任意的成员函数,包括const成员函数。

const Demo de;
de.set()//error
de.print()//ok

//!!!!!
void func(const Demo& de)
{
  de.get();//ok
  de.set();//error
}

 

猜你喜欢

转载自www.cnblogs.com/quehualin/p/9204900.html