c++ const 成员函数

const 修饰成员函数表示传入函数内的为 const *this

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 Demo *this */) const //相当于传入了一个const 的this指针
{
    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
}

 

 

const Vec2& getPosition const;

(1),第一个const表示,返回值引用只读

(2),第二个const表示,该成员函数内部不会修改成员变量

posted @ 2018-06-20 17:23  -南  阅读(312)  评论(0编辑  收藏  举报