c++之const修饰成员函数

时间:2022-07-23
本文章向大家介绍c++之const修饰成员函数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

常函数:

  • 成员函数后加const后我们称这个函数为常函数;
  • 常函数不可以修改成员属性
  • 成员属性声明时加关键字mutable后,在常函数中依然可以修改

常对象:

  • 声明对象前加const
  • 常对象只能调用常函数

常函数:

#include<iostream>
using namespace std;
class Person {
public:
    int age;
    mutable int tmp;//用mutable修饰的为特殊变量,可以在常量函数中修改
    void showPerson() const{
        //this指针的本质是指针常量,指针的指向是不可以修改的
        this = NULL;
        //即Person* const this;
        //在函数后面加了const之后,变成const Person* const this
        //此时,既不可以修改指向,也不可以修改值
        this->age = 100;
        this->tmp = 200;
    }
};
int main() {
    Person p;
    p.showPerson();
    system("pause");
    return 0;
}

说明:红色标注的是编译报错的,紫色标注的是可以成功编译的。

常对象:

#include<iostream>
using namespace std;
class Person {
public:
    int age;
    mutable int tmp;//用mutable修饰的为特殊变量,可以在常量函数中修改
    void showPerson() const{
        cout << "这是常函数" << endl;
    }
};
void test() {
    const Person p;//在对象前加const,变为常对象
    //常对象不能调用普通成员变量
    p.age = 10;
    //特殊变量,在常对象下也可以修改
    p.tmp = 20;
    //常对象只能调用常函数
    p.showPerson();
}
int main() {
    test();
    system("pause");
    return 0;
}

说明:红色标注的是编译报错的,紫色标注的是可以成功编译的。