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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值