1 C++中的const成员函数
1.1 const成员函数的使用
对于一个const对象来说,是不能调用普通的成员函数的。因为,C++认为,const(常量)对象,如果允许去调用普通的成员函数,而这个成员函数内部可能会修改这个对象的数据成员!而这将导致const对象不再是const对象!
const对象只能调用const成员函数, 如果一个成员函数内部,不会修改任何数据成员,就把它定义为const成员函数。const成员函数内,不能修改任何数据成员!
const成员函数的定义:

const成员函数示例:
// test.h
class Test
{
public:
int getCount() const;
private:
int count;
};
// test.cpp
int Test::getCount() const
{
return count;
}
1.2 同名的const成员函数和非const成员函数构成重载关系
Class A {
int function ();
int function () const;
};
如上的示例代码中两个function函数构成了重载关系,本质是函数参数的不同,一个为const类型的this指针传递,另一个为非const类型的this指针传递。
2 mutable关键字
mutable关键字:
- mutable是为了突破const函数的限制而设计的。
- mutable成员变量将永远处于可改变的状态。
- mutable在实际的项目开发中被严禁滥用。
mutable的深入分析:
- mutable成员变量破坏了只读对象的内部状态。
- const成员函数保证只读对象的状态不变性。
- mutable成员变量的出现无法保证状态不变性。
mutable关键可以用来解决如下问题:如何统计某个成员变量的访问次数?
#include <iostream>
#include <string>
using namespace std;
class Test
{
int m_value;
mutable int m_count;
public:
Test(int value = 0)
{
m_value = value;
m_count = 0;
}
int getValue() const
{
m_count++;
return m_value;
}
void setValue(int value)
{
m_count++;
m_value = value;
}
int getCount() const
{
return m_count;
}
~Test()
{
delete m_pCount;
}
};
int main(int argc, char *argv[])
{
Test t;
t.setValue(100);
cout << "t.m_value = " << t.getValue() << endl;
cout << "t.m_count = " << t.getCount() << endl;
const Test ct(200);
cout << "ct.m_value = " << ct.getValue() << endl;
cout << "ct.m_count = " << ct.getCount() << endl;
return 0;
}
上述问题还有更好的解决方案:
#include <iostream>
#include <string>
using namespace std;
class Test
{
int m_value;
int * const m_pCount;
/* mutable int m_count; */
public:
Test(int value = 0) : m_pCount(new int(0))
{
m_value = value;
/* m_count = 0; */
}
int getValue() const
{
/* m_count++; */
*m_pCount = *m_pCount + 1;
return m_value;
}
void setValue(int value)
{
/* m_count++; */
*m_pCount = *m_pCount + 1;
m_value = value;
}
int getCount() const
{
/* return m_count; */
return *m_pCount;
}
~Test()
{
delete m_pCount;
}
};
int main(int argc, char *argv[])
{
Test t;
t.setValue(100);
cout << "t.m_value = " << t.getValue() << endl;
cout << "t.m_count = " << t.getCount() << endl;
const Test ct(200);
cout << "ct.m_value = " << ct.getValue() << endl;
cout << "ct.m_count = " << ct.getCount() << endl;
return 0;
}
参考资料:
2749

被折叠的 条评论
为什么被折叠?



