C++关键字的详解 ---- mutable关键字
2015-10-13 20:37
267 查看
mutable的中文翻译是:易变的,性情不定的,跟constant(既C++中的const)是反义词.
在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中.
例子解释
显然temp++不能用在const修饰的函数里.
计数器temp被mutable修饰,那么它就可以突破const的限制,在被const修饰的函数里面也能被修改.
在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中.
例子解释
#include <iostream> using namespace std; class HuangwenMutable { public: huangwenMutable(){temp=0;} int Output() const { return temp++; //error C2166: l-value specifies const object } private: int temp; }; int main() { HuangwenMutable huangwenMutable; cout<<huangwenMutable.Output()<<endl; return 0; }
显然temp++不能用在const修饰的函数里.
#include <iostream> using namespace std; class HuangwenMutable { public: huangwenMutable(){temp=0;} int Output() const { return temp++; //error C2166: l-value specifies const object } private: mutable int temp; }; int main() { HuangwenMutable huangwenMutable; cout<<huangwenMutable.Output()<<endl; return 0; }
计数器temp被mutable修饰,那么它就可以突破const的限制,在被const修饰的函数里面也能被修改.
相关文章推荐
- c#入门经典1~4章 与c++的对比
- Dlib库的安装配置
- 【C++】观察者模式
- C++中进程间相互通信的十一种方法(转)
- C++高质量编程笔记
- C语言基础知识进阶(中)
- 带你玩转Visual Studio——带你跳出坑爹的Runtime Library坑
- C++中的Sleep函数分析
- C++和C混合编程
- C++:IO标志位
- C语言void泛型指针
- C语言中auto、register、static、const、volatile、extern的区别
- 关于C++递归函数的学习总结
- C++STL之map映照容器
- 【C++】指针&引用的区别
- VC++ MFC中多线程
- c++内存对象模型(非常详细)
- leetcode284 : Peeking Iterator
- C++__类模板的派生
- C++之鸡零狗碎