当前位置:首页 > 通信资讯 > 正文

C++mutable(mutable对象有哪些)

代码编译运行环境:VS2017+Win32+Debug

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

mutable的作用有两点:

(1)保持常量对象中大部分数据成员仍然是“只读”的情况下,实现对个别数据成员的修改;
(2)使类的const函数可以修改对象的mutable数据成员。

使用mutable的注意事项:

(1)mutable只能作用于类的非静态和非常量数据成员。
(2)在一个类中,应尽量或者不用mutable,大量使用mutable表示程序设计存在缺陷。

示例代码如下:

?
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 32 33 34 35 #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(); return 0; }

程序输出结果:

张三
1

mutable不能修饰const数据成员容易理解,因为mutable与const本是反义,同时修饰不是自相矛盾吗。mutable不能修饰static数据成员,因为static数据成员存储在Data段或BSS段,属于类,不属于类对象,那么常对象和常函数可以对其任意地修改,所以类的static数据成员根本不需要mutable的修饰,但对于常对象的数据成员则不可以被修改,若想修改,则需要mutable的修饰。示例代码如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #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();//常函数修改 return 0; }

程序输出结果是:

5
15

以上就是详解C++中mutable的用法的详细内容,更多关于C++ mutable的资料请关注服务器之家其它相关文章!

原文链接:https://cloud.tencent.com/developer/article/1394373

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。