C++中的 mutable 关键字

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
*/
复制代码

 

posted on   Hello-World3  阅读(218)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2022-12-22 RCU-1——内核文档翻译——Data-Structures.rst
2021-12-22 attribute section 属性
2018-12-22 Linux块设备驱动_WDS

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示