您的位置:首页 > 编程语言 > C语言/C++

C++中mutable关键字的用法

2015-08-27 17:12 435 查看
代码编译运行环境:VS2012+Win32+Debug

mutalbe的中文意思是“可变的,易变的”,是constant(即C++中的const)的反义词。在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量将永远处于可变的状态。

mutable的作用有两点:

(1)保持长量对象中大部分数据成员仍然是“只读”的情况

下,实现对个别数据成员的修改。

(2)使const函数可修改对象的mutable数据成员。

使用mutable的注意事项:

(1)mutable只能作用于类的非静态和非常量数据成员。

(2)在一个类中,应尽量或者不用mutable,大量使用mutable表示程序设计存在缺陷。

示例代码如下:

#include <iostream>
using namespace std;

//mutable int test;//编译出错

class Student{
string name;
mutable int getNum;
//mutable const int test;    //编译出错
//mutable static int static1;//编译出错
public:
Student(char* name){
this->name=name;
getNum=0;
}
string getName()const {
++getNum;
return name;
}
void pintTimes() const{
cout<<getNum<<endl;
}
};
int main(int argc, char* argv[])
{
const Student s("张三");
cout<<s.getName().c_str()<<endl;
s.pintTimes();
getchar();
return 0;
}


程序输出结果:

张三

1

这里提个问题,mutable不能修饰const数据成员容易理解,因为mutable与const本是反义,同时修饰不是自相矛盾吗。但是为什么mutable不能修饰static数据成员呢?

因为static数据成员存储在全局静态存储区,属于类,不属于类对象,那么常对象和常函数对其可以任意的修改,所以类的static数据成员根本不需要mutable的修饰。但对于常对象的数据成员则不可以被修改,若想修改,则需要mutable的修饰。

示例代码如下:

#include <iostream>
using namespace std;

class Student{
string name;
public:
static int test1;
void modify() const{
test1=15;
cout<<test1<<endl;
}
};

int Student::test1;//申明test1并按照编译器默认的值进行初始化
int main(int argc, char* argv[])
{
const Student s("张三");
s.test1=5;//常对象可以修改静态类的数据成员test1
cout<<Student::test1<<endl;
s. modify();//常函数修改
getchar();
return 0;
}


程序输出结果是:

5

15

参考文献

[1]C++高级进阶教程.陈刚.武汉大学出版社.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: