const對象與const成員函數

const對象只能調用const成員函數:

#include<iostream>
using namespace std;
class A  
{  
public:  
	void fun()const
	{
		cout<<"const 成員函數!"<<endl;
		}
	void fun()
	{
		cout<<"非const成員函數 !"<<endl;
	}
};  
int main()
{
	const A a;
	a.fun();
}

輸出:const 成員函數!

但是如果把第以1個fun註釋掉就會出錯:error C2662: “A::fun”: 不能將“this”指針從“const A”轉換爲“A &”。

但是const成員函數可以被非const 對象調用:

#include<iostream>
using namespace std;
class A  
{  
public:  
	void fun()const
	{
		cout<<"const 成員函數!"<<endl;
		}	

/*	void fun()
	{
		cout<<"非const成員函數 !"<<endl;
	}
	*/
};  
int main()
{
	 A a;
	a.fun();
}

該段代碼輸出:const 成員函數!

當然非const對象可以調用非const成員函數。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章