44.继承

继承:

c++最重要的特征是代码重用,通过继承机制可以利用已有的数据类型来定义新的数据类型,新的类不仅拥有旧类的成员,还拥有新定义的成员。
一个B类继承于A类,或称从类A派生类B。这样的话,类A成为基类(父类), 类B成为派生类(子类)。
 

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

//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();
//
//}

//继承写法
//抽象一个 基类的网页  重复的代码都写到这个网页上
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;
}

输出

 新闻网页内容:
公共头部
公共底部
左侧列表
新闻播放
 娱乐网页内容:
公共头部
公共底部
左侧列表
白百合。。。
 游戏网页内容:
公共头部
公共底部
左侧列表
KPL直播

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值