c++const成员函数*

一:知识点:

成员函数末尾增加const
1)该函数被称为常量成员函数
2)在函数的定义和声明处的末尾都要加const
3)该成员函数不能修改类中的任何成员(非mutable修饰的任意成员属性)
4)const 类型的类变量,不能调用非常量成员函数
5)const和非const类变量,可以调用常量成员函数(const成员函数可被更多场景使用
6)如果成员属性希望在任意函数中都可以被修改,那么该属性应该被声明为mutable.

二:例子:

#include <iostream>
#include <string>
using namespace std;

class Person {
   public:
    int id;
    string name;
    // 在常量成员函数中也可以被修改, mutable和int的前后顺序没关系
    mutable int mt;

   public:
    Person() {
        this->id = 200;
        cout << "wu can gou zao han shu" << endl;
    }

    void PrintPersonConst() const;
    void PrintPerson() {}
    Person(int id);
};

void Person::PrintPersonConst() const {
    // mutable属性可在常量函数中被修改
    this->mt = 200;
}

int main(int argc, char const* argv[]) {
    const Person pConst;
    // 这里是类常量变量调用了非常量函数,所以会报错
    // pConst.PrintPerson();

    Person p2;
    //类的普通变量可以调用常量函数
    p2.PrintPerson();
    pConst.PrintPersonConst();
}
原文地址:https://www.cnblogs.com/qiumingcheng/p/15519357.html