const成员函数

#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 成员函数吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值