C++ 关键字之 mutable

  • mutalbe的中文意思是“可变的,易变的”,跟constant(既C++中的const)是反义词。 在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中。
  • 我们知道,如果类的成员函数不会改变对象的状态,那么这个成员函数一般会声明成const的。但是,有些时候,我们需要在const的函数里面修改一些跟类状态无关的数据成员,那么这个数据成员就应该被mutalbe来修饰。

mutable的作用有两点:

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

示例代码1

#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("张三");//const对象只能访问const成员函数
	cout<<s.getName().c_str()<<endl;
	s.pintTimes();
	return 0;
}
//程序输出结果
//张三
//1

使用mutable的注意事项:

  1. mutable只能作用于类的非静态(static)和非常量(const)数据成员。
    • 静态数据成员存储在Data段或BSS段(静态存储区),属于类,不属于类对象,那么常对象和常函数可以对其任意地修改,所以类的static数据成员根本不需要mutable的修饰,但对于常对象的数据成员则不可以被修改,若想修改,则需要mutable的修饰
    • 因为const 和 mutable 是矛盾的,所以不能同时作用
  2. 在一个类中,应尽量或者不用mutable,大量使用mutable表示程序设计存在缺陷。

示例代码2

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值