# day-07 继承1.0

继承的定义

继承是面向对象三大特性之一

我们发现,定义这些类时,下级别的成员除了拥有上一级的共性,还有自己的特性。
利用继承的技术,减少重复代码

继承的优点:可以减少重复的代码

格式:class A : public B;

A 类称为子类 或 派生类
B 类称为父类 或 基类

#include <iostream>
using namespace std;
#include <string>

//公共页面
class BasePage{
    
    
public:
	void header(){
    
    
		cout << "首页、公开课、登录、注册...(公共头部)" << endl;
	}
	void footer(){
    
    
		cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;
	}
	void left(){
    
    
		cout << "Java,Python,C++...(公共分类列表)" << endl;
	}
};

class Java : public BasePage{
    
    
public:
	void content(){
    
    
		cout << "JAVA学科视频" << endl;
	}
};

class Python : public BasePage{
    
    
public:
	void content(){
    
    
		cout << "Python学科视频" << endl;
	}
};

class CPP : public BasePage{
    
    
public:
	void content(){
    
    
		cout << "C++学科视频" << endl;
	}
};

void test01(){
    
    
	cout << "Java下载视频页面如下: " << endl;
	Java ja;
	ja.header();
	ja.footer();
	ja.left();
	ja.content();
	cout << "--------------------" << endl;

	cout << "Python下载视频页面如下: " << endl;
	Python py;
	py.header();
	py.footer();
	py.left();
	py.content();
	cout << "--------------------" << endl;

	cout << "C++下载视频页面如下: " << endl;
	CPP cp;
	cp.header();
	cp.footer();
	cp.left();
	cp.content();

}

int main() {
    
    
	test01();
	system("pause");
	return 0;
}

# 二级目录
# 级目录




继承的方式

在这里插入图片描述
公有继承:父类中的私有属性不能访问,其余不变
保护继承:父类中的公有和保护权限都变成保护权限,父类中的私有属性不能访问
私有继承:父类中的公有和保护权限都变为保护权限,父类中的私有属性不能访问

注意

私有继承

class Son3:private Base3

公有继承son3

class GrandSon3 :public Son3

//Son3是私有继承,所以继承Son3的属性在GrandSon3中都无法访问到

继承中的对象模型

1.

#include <iostream>
using namespace std;

class Base{
    
    
public:
	int m_A;
protected:
	int m_B;
private:
	int m_C; //私有成员只是被隐藏了,但是还是会继承下去
};

class Son :public Base{
    
    
public:
	int m_D;
};

void test(){
    
    
	cout << "sizeof Son = " << sizeof(Son) << endl;
}

int main() {
    
    
	test();
	system("pause");
	return 0;
}

运行结果:一个int占 4 个字节
在这里插入图片描述

结论: 父类中私有成员也是被子类继承下去了,只是由编译器给隐藏后访问不到

2.可以通过vs自带的开发人员命令提示符查看单个类所占字节
在这里插入图片描述

打开当前文件夹,找到路径
在这里插入图片描述

在这里插入图片描述

继承中的构造和析构顺序

#include <iostream>
using namespace std;

class Base{
    
    
public:
	Base(){
    
    
		cout << "Base构造函数" << endl;
	}
	~Base(){
    
    
		cout << "Base析构函数" << endl;
	}
};

class Son : public Base{
    
    
public:
	Son(){
    
    
		cout << "Son构造函数" << endl;
	}
	~Son(){
    
    
		cout << "Son析构函数" << endl;
	}
};

void test(){
    
    
	Son s;
}

int main() {
    
    
	test();
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

总结:继承中,先调用父类构造函数,再调用子类构造函数,析构顺序相反

猜你喜欢

转载自blog.csdn.net/weixin_48245161/article/details/113182531