const修饰成员函数,常函数,常对象

设计关键字:const、mutable

常函数:

- 成员函数后面加const,就是常函数

- 常函数里面不能修改成员变量的值

- 成员变量加mutable修饰,在常函数中可以修改

 

常对象:

- 声明对象前加入const进行修饰,即常对象

- 常对象只能调用常函数

 

class Person {
public:
    Person() {
        m_A = 0;
        m_B = 0;
    }

    //this指针的本质是一个指针常量,指针的指向不可修改
    //如果想让指针指向的值也不可以修改,需要声明常函数
    void ShowPerson() const {
        //const Type* const pointer;
        //this = NULL; //不能修改指针的指向 Person* const this;
        //this->mA = 100; //但是this指针指向的对象的数据是可以修改的

        //const修饰成员函数,表示指针指向的内存空间的数据不能修改,除了mutable修饰的变量
        this->m_B = 100;
    }

    void MyFunc() const {
        //mA = 10000;
    }

public:
    int m_A;
    mutable int m_B; //可修改 可变的
};


//const修饰对象  常对象
void test01() {

    const Person person; //常量对象
    cout << person.m_A << endl;
    //person.mA = 100; //常对象不能修改成员变量的值,但是可以访问
    // person.m_B = 100; //但是常对象可以修改mutable修饰成员变量
    person.ShowPerson();
    cout << person.m_B << endl;
    //常对象访问成员函数
    person.MyFunc(); //常对象不能调用const的函数

}

int main() {

    test01();

    return 0;
}

 

posted @ 2022-09-21 18:43  何侠客  阅读(59)  评论(0编辑  收藏  举报