在c++中,如果成员函数被const关键字修饰,那么调用这个成员函数将不会改变对象的任何状态(任何成员变量的值)。
但是如果我们需要在const修饰的函数里面修改一些成员变量,那么这个成员变量可以使用mutalbe来修饰。这样的话,这个变量就可以突破const的限制,在被const修饰的函数里面也能被修改。
例子如下:
#include <QCoreApplication>
#include "iostream"
using namespace std;
class Test
{
public:
Test();
~Test();
void Print() const; //const成员函数
int PrintTimes() const; //const成员函数
private:
mutable int ptimes; //mutable 意为:可变的
};
Test::Test()
{
ptimes = 0;
}
Test::~Test()
{
}
void Test::Print() const
{
cout << "This is a test message!" << endl;
ptimes++;
}
int Test::PrintTimes() const
{
return ptimes;
}
void myTest(Test const* ClassPointer) //对指针的常量引用
{
cout << ClassPointer->PrintTimes() << endl;
ClassPointer->Print();
cout << ClassPointer->PrintTimes() << endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Test* test=new Test;
myTest(test);
return a.exec();
}