c++從入門到精通——繼承的引出

繼承的引出

面向對象程序設計中最重要的一個概念是繼承。繼承允許我們依據另一個類來定義一個類,這使得創建和維護一個應用程序變得更容易。這樣做,也達到了重用代碼功能和提高執行效率的效果。

當創建一個類時,您不需要重新編寫新的數據成員和成員函數,只需指定新建的類繼承了一個已有的類的成員即可。這個已有的類稱爲基類,新建的類稱爲派生類。

繼承代表了 is a 關係。例如,哺乳動物是動物,狗是哺乳動物,因此,狗是動物,等等。

普通寫法

class News
{
public:
	void header()
	{
		cout << "公共頭部" << endl;
	}
	void footer()
	{
		cout << "公共底部" << endl;
	}
	void left()
	{
		cout << "左側列表" << endl;
	}

	void content()
	{
		cout << "新聞播放" << endl;
	}

};

class YULE
{
public:
	void header()
	{
		cout << "公共頭部" << endl;
	}
	void footer()
	{
		cout << "公共底部" << endl;
	}
	void left()
	{
		cout << "左側列表" << endl;
	}

	void content()
	{
		cout << "白百合。。。" << endl;
	}

};

void test01()
{
	News news;
	news.header();
	news.footer();
	news.left();
	news.content();

	//娛樂頁
	YULE yl;
	yl.header();
	yl.footer();
	yl.left();
	yl.content();

}

繼承寫法

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

//繼承寫法
//抽象一個 基類的網頁  重複的代碼都寫到這個網頁上
class BasePage
{
public:
	void header()
	{
		cout << "公共頭部" << endl;
	}
	void footer()
	{
		cout << "公共底部" << endl;
	}
	void left()
	{
		cout << "左側列表" << endl;
	}
};

class News :public BasePage //繼承  News類 繼承於 BasePage類
{
public:
	void content()
	{
		cout << "新聞播放" << endl;
	}
};

class YULE :public BasePage
{
public:
	void content()
	{
		cout << "白百合。。。" << endl;
	}
};

class Game :public BasePage
{
public:
	void content()
	{
		cout << "KPL直播" << endl;
	}
};


void test02()
{
	cout << " 新聞網頁內容: " << endl;
	News news;
	news.header();
	news.footer();
	news.left();
	news.content();

	cout << " 娛樂網頁內容: " << endl;
	YULE yl;
	yl.header();
	yl.footer();
	yl.left();
	yl.content();


	cout << " 遊戲網頁內容: " << endl;
	Game game;
	game.header();
	game.footer();
	game.left();
	game.content();

}

//繼承 減少代碼重複內容
//BasePage  基類 (父類)   News 派生類 (子類)



int main(){

	//test01();

	test02();

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