一:知识点:

成员函数末尾增加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();
}

相关文章:

  • 2021-05-25
  • 2021-09-05
  • 2022-12-23
  • 2021-07-01
  • 2021-08-01
  • 2021-10-03
  • 2021-09-04
猜你喜欢
  • 2021-11-05
  • 2021-07-21
  • 2021-11-08
  • 2022-03-03
  • 2021-11-25
  • 2021-06-30
相关资源
相似解决方案