首页 > 编程语言 > 详细

C++中如何可以修改const函数内的成员变量的值?

时间:2016-05-17 19:17:28      阅读:219      评论:0      收藏:0      [点我收藏+]


呵呵,你使用mutable关键字来定义变量就可以了。
下面举例说明


C++关键字mutable

Mutable

(1)mutable的意思是“可变的,易变的”,跟C++中的const是反义词。

(2)在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中

实例说明:

复制代码
#include <iostream>
using namespace std;

class TestMutable
{
public:
TestMutable(){i=0;}
int Output() const
{
return i++; //error C2166: l-value specifies const object
}
private:
int i;
};

int main()
{
TestMutable testMutable;
cout<<testMutable.Output()<<endl;
return 0;
}
复制代码
显然i++在const修饰的函数里是编译通不过的。

复制代码
#include <iostream>
using namespace std;

class TestMutable
{
public:
TestMutable(){i=0;}
int Output() const
{
return i++;
}
private:
mutable int i;
};

int main()
{
TestMutable testMutable;
cout<<testMutable.Output()<<endl;
return 0;
}
复制代码
在 int i 前面加上 mutable上面就能编译通过了,马上可以看出关键字mutable的作用了。

C++中如何可以修改const函数内的成员变量的值?

原文:http://www.cnblogs.com/gylhaut/p/5502583.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!