C++ const常量成员函数,this指针的本质

C++ const常量成员函数,this指针的本质

C++ pririmer第七章:默认情况下,this的类型是指向类类型非常量版本的常量指针。也就是说如果现在有一个类student,那么其this指针类型为student *const,不能用this去指向其他对象。根据c++规则:想存放常量对象的地址,只能使用指向常量的指针,也就意味着其不能在一个常量对象上调用普通的成员函数。如下情况是不允许的:

class people{
public:
    people(){}
    people(int x) :score(x){}
    ~people(){}
    int getScore(){ return score; }
private:
    int score;
};
int main()
{
    const people p1(22);
    cout << p1.getScore() << endl;//error
    system("pause");
    return 0;
}

C++语言的做法是允许把const关键字放在成员函数的参数列表之后,此时,紧跟在参数列表后面的const表示this是一个指向常量的指针。像这样使用const的成员函数被称作常量成员函数。

class people{
public:
    //...
    int getScore() const{ return score; }
    //...
};
int main()
{
    const people p1(22);
    cout << p1.getScore() << endl;//ok
    system("pause");
    return 0;
}

相当于现在this指针的类型是const people *const,是可以绑定常量与非常量的,所以把this设置为指向常量的指针有助于提高函数的灵活性。

mutable在const成员函数内也可被更改。

你可能感兴趣的:(c++,开发语言,后端)