C++-----对象的继承(一)

本文深入探讨C++中的对象继承概念,详细解释了如何创建派生类并使用基类的属性和方法。通过实例说明了继承在软件设计中的作用,帮助读者理解面向对象编程中的继承机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include <iostream>

using namespace std;

//继承:
//减少代码的重复性;

//网页实例:
class news
{
public:
	void head()
	{
		cout << "公共的头部" << endl;
	}
	void footer()
	{
		cout << "公共的底部" << endl;
	}
	void left()
	{
		cout << "左侧列表" << endl;
	}
	void content()
	{
		cout << "新闻播报" << endl;
	}
};

class Entertainment
{
public:
	void head()
	{
		cout << "公共的头部" << endl;
	}
	void footer()
	{
		cout << "公共的底部" << endl;
	}
	void left()
	{
		cout << "左侧列表" << endl;
	}
	void content()
	{
		cout << "娱乐" << endl;
	}
};

void test01()
{
	news m_new;
	m_new.head();
	m_new.footer();
	m_new.left();
	m_new.content();
	Entertainment m_ent;
	m_ent.head();
	m_ent.footer();
	m_ent.left();
	m_ent.content();
}

//避免代码冗余,所以提前抽象一个基类网页;
//重复的代码写到这个基类网页上;

class basePage
{
public:
	void head()
	{
		cout << "公共的头部" << endl;
	}
	void footer()
	{
		cout << "公共的底部" << endl;
	}
	void left()
	{
		cout << "左侧列表" << endl;
	}

};

class news2 : public basePage   //继承的写法,表示news2类继承于basePage;
{
public:
	void content()
	{
		cout << "新闻播报" << endl;
	}

};

class entertainment2 :public basePage
{
public:
	void content()
	{
		cout << "娱乐" << endl;
	}

};

class Game :public basePage
{
public:
	void content()
	{
		cout << "游戏直播" << endl;
	}
	
};

void test02()
{
	entertainment2 m_ent2;
	news2 m_new2;
	Game m_game;
	m_ent2.content();
	m_new2.content();
	m_game.content();
}

int main()
{
	test01();
	test02();
    return 0;
}

//上述的basePage 叫做 基类(父类),其余的 news2,entertainment2 , Game 叫做派生类(子类);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值