#include <iostream>
using namespace std;
class Widget
{
public:
Widget(int value):m_value(value){}
int GetValue()const // 成员函数的const版本
{
cout << "IN : int GetValue()const" << endl;
return m_value;
}
int GetValue() // 成员函数的非const版本
{
cout << "IN : int GetValue()" << endl;
return m_value;
}
private:
int m_value;
};
int GetWidget(const Widget* cpWidget)
{
cout << "IN : int GetWidget(const widget* cpWidget) "<< endl;
return cpWidget->GetValue();
}
int GetWidget(Widget* pWidget)
{
cout<<"IN : int GetWidget(widget* pWidget)"<<endl;
return pWidget->GetValue();
}
void main()
{
Widget *pWidget1 = new Widget(4);
GetWidget(pWidget1);
const Widget *pWidget2 = new Widget(5);
GetWidget(pWidget2);
}
运行结果:
如果将const 成员函数删除,程序编译不能通过。
这说明了:
1. const 成员函数是供 const 对象 调用的。
2. const 对象不能调用 非const 的成员函数
3. 非const 对象 优先调用 成员函数的非const版本。在没有 非const版本 的时候 会去调用 成员函数的 const 版本。
综上所述:如果 成员函数并没有改变 对象的意图的话,就将之设为 const 成员函数吧!