C++類中的重載、覆蓋和隱藏

之前學C++其實只知道重載這個概念,對於覆蓋和隱藏就不知道是神馬了,昨天的面試題遇到這個問題。後來上網看看,其實自己還是知道這些規則的。下面來講講,權當鞏固知識了。

C++類中成員函數的重載。
其實重載就是將函數取個相同的名字罷了,但是參數類型、參數個數以及返回類型要有所差異。重載主要在對不同數據類型進行相同的操作時用的比較多。
重載的例子:

#include <iostream>
using namespace std;

class Father
{
public:
	void func(int num)
	{
		cout<<"The num is "<<num<<endl;
	}
	void func(float num)
	{
		cout<<"The num is "<<num<<endl;
	}
};

int main()
{
	Father father;
	father.func(5);
	father.func((float)5.1);
	return 0;
}

覆蓋其實是指在使用多態時,派生類函數會覆蓋掉基類的虛函數,其實就是指多態啦!
覆蓋的例子:

#include <iostream>
using namespace std;

class Father
{
public:
	virtual void func()
	{
		cout<<"This is Father!"<<endl;
	}
};

class Child : public Father
{
public:
	void func()
	{
		cout<<"This is Child!"<<endl;
	}
};

int main()
{
	Father father;
	Child child;
	Father *fp;
	fp = &father;
	fp->func();
	fp = &child;
	child.func();
	return 0;
}

/*結果
This is Father!
This is Child!
*/

至於隱藏嘛,我的理解就是多態的功能不能體現,派生類的函數無法覆蓋基類同名函數,這樣在多態的時候,派生類的函數就被隱藏了。
下面兩種情況就都會產生隱藏現象:
1)基類函數沒有聲明爲虛函數(沒有加virtual),派生類有跟它一模一樣的函數聲明。
2)派生類中的函數與基類中的函數同名,但是參數或者返回值不相同,則不管基類中這個函數是不是虛函數,都會產生隱藏現象。
隱藏的例子:

#include <iostream>
using namespace std;

class Father
{
public:
	void func1()
	{
		cout<<"This is Father::func1!"<<endl;
	}
	void func2()
	{
		cout<<"This is Father::func2!"<<endl;
	}
};

class Child : public Father
{
public:
	void func1()
	{
		cout<<"This is Child::func1!"<<endl;
	}
	int func2()
	{
		cout<<"This is Child::func2!"<<endl;
		return 0;
	}
};

int main()
{
	Father father;
	Child child;
	Father *fp;
	fp = &father;
	fp->func1();
	fp->func2();
	fp = &child;
	fp->func1();   //產生隱藏的第一種情況
	fp->func2();   //產生隱藏的第二種情況
	return 0;
}

/*結果
This is Father::func1!
This is Father::func2!
This is Father::func1!
This is Father::func2!
*/



 

發佈了42 篇原創文章 · 獲贊 30 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章