C++中的 mutable 关键字

发布时间 2023-12-22 17:37:20作者: Hello-World3

Parcel 类中 mDataPos 被修饰为 mutable 类型变量。

C++ 中的 mutable 是一个关键字,用于修饰类的成员变量。mutable 关键字的作用是允许被修饰的成员变量在 const 修饰的成员函数中被修改,即使这些函数被声明为 const。

下面是 mutable 关键字的使用示例:

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass(int c):counter(c){}
    /* 声明为const函数,表示不会修改类的成员属性,但是mutable的属性除外 */
    int getValue() const;
private:
    mutable int counter;
};

int MyClass::getValue() const {
    counter++;  // 允许在 const 成员函数中修改 mutable 成员变量
    return counter;
}

int main()
{
    MyClass mc = 10;
    cout << mc.getValue() << endl;
    return 0;
}

/*
4.mutable$ ./pp
11
*/