const成员函数修改类成员的办法

关键字:C++, mutable

 本文主要说明如何在一个const成员函数中修改类的成员变量,本人在阅读当中偶得,不见得对各位有多大实用价值。针对菜鸟,老鸟们不用看了。

 大家知道如果把一个类的成员函数声明为const,则表示该函数不会修改类的成员变量,像下面这样:
class ConstFunc
{
public:
 ConstFunc(){i = j = 1;};
 void ConstFunction() const;
 void Tell() const;
private:
 int i;
 int j;
};

void ConstFunction() const
{
 cout << "i=" << i << ", j=" << j << endl;
}

void ConstFunction() const
{
 //i ++;  //Would cause an error
 //j ++;  //Would cause an error
}

void main()
{
 ConstFunc myConstFunc;
 myConstFunc.f();
 myConstFunc.Tell();
}
 

 《C++编程思想》7.4.3节里,作者提到一个C++关键字mutable,用这个修饰符限定的变量可以被一个声明为const的成员函数修改。上面例子略作修改如下:

class ConstFunc
{
public:
 ConstFunc(){i = j = 1;};
 void ConstFunction() const;
 void Tell() const;
private:
 int i;
 mutable int j;  //Declared as mutable here
};

void ConstFunction() const
{
 cout << "i=" << i << ", j=" << j << endl;
}

void ConstFunction() const
{
 //i ++;  //Would cause an error
 j ++;  //OK here!
}

void main()
{
 ConstFunc myConstFunc;
 myConstFunc.f();
 myConstFunc.Tell();
}

 小弟才疏学浅,还没有碰上实际当中运用mutable关键字的现象。
 另外稍稍提醒,const的用法大家都熟了吗?不妨看看下面的小测试吧:
 请分别说明下面声明的含义:
const int* x;
int const* x;
int* const x;
const int* const x;
int const* const x;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值