40.继承的概念
1.为什么要有继承
//网页类
class IndexPage{
public:
//网页头部
void Header(){
cout << "网页头部!" << endl;
}
//网页左侧菜单
void LeftNavigation(){
cout << "左侧导航菜单!" << endl;
}
//网页主体部分
void MainBody(){
cout << "首页网页主题内容!" << endl;
}
//网页底部
void Footer(){
cout << "网页底部!" << endl;
}
private:
string mTitle; //网页标题
};
#if 0
//如果不使用继承,那么定义新闻页类,需要重新写一遍已经有的代码
class NewsPage{
public:
//网页头部
void Header(){
cout << "网页头部!" << endl;
}
//网页左侧菜单
void LeftNavigation(){
cout << "左侧导航菜单!" << endl;
}
//网页主体部分
void MainBody(){
cout << "新闻网页主体内容!" << endl;
}
//网页底部
void Footer(){
cout << "网页底部!" << endl;
}
private:
string mTitle; //网页标题
};
void test(){
NewsPage* newspage = new NewsPage;
newspage->Header();
newspage->MainBody();
newspage->LeftNavigation();
newspage->Footer();
}
#else
//使用继承,可以复用已有的代码,新闻业除了主体部分不一样,其他都是一样的
class NewsPage : public IndexPage{
public:
//网页主体部分
void MainBody(){
cout << "新闻网页主主体内容!" << endl;
}
};
void test(){
NewsPage* newspage = new NewsPage;
newspage->Header();
newspage->MainBody();
newspage->LeftNavigation();
newspage->Footer();
}
#endif
int main(){
test();
return EXIT_SUCCESS;
}
2.继承基本概念
c++最重要的特征是代码重用,通过继承机制可以利用已有的数据类型来定义新的数据类型,新的类不仅拥有旧类的成员,还拥有新定义的成员。
一个B类继承于A类,或称从类A派生类B。这样的话,类A成为基类(父类), 类B成为派生类(子类)。
派生类中的成员,包含两大部分:
●一类是从基类继承过来的,一类是自己增加的成员。
● 从基类继承过过来的表现其共性,而新增的成员体现了其个性。
3.派生类定义
派生类定义格式
Class 派生类名 : 继承方式 基类名{
//派生类新增的数据成员和成员函数
}
三种继承方式:
■public : 公有继承
■private : 私有继承
■protected : 保护继承
从继承源上分:
● 单继承:指每个派生类只直接继承了一个基类的特征
●多继承:指多个基类派生出一个派生类的继承关系,多继承的派生类直接继承了不止一个基类的特征
4.视频内容
程序:
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS 1
//2022年10月15日19:53:34
#include <iostream>
using namespace std;
//继承的作用1.代码复用。2.扩展类的功能
class Father
{
public:
void func1()
{
cout << "约小姐姐" << endl;
}
void func2()
{
cout << "有钱" << endl;
}
};
class Son:public Father
{
public:
void func3()
{
cout << "约小姐姐" << endl;
}
};
void test()
{
Son s;
s.func1();
s.func2();
}
int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}
输出结果:
约小姐姐
有钱
请按任意键继续. . .
参考资料
参考资料来源于黑马程序员等