在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();
}