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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章