我的物联网之路——C++——继承

继承

继承是允许重用现有类来构造新类的特性
优点:
代码的可重用性,重定义基类的成员函数,向派生类添加新成员
可分为:
单一继承、多级继承、多重继承、层次继承

继承的实现

派生类的声明必须指定基类的名称
派生类:访问控制权限说明符 基类
ex: class Managet : public Empyloyee

基类

基类分为两种类型
直接基类
间接基类
ex:
class A{};
class B : public class A{};
class C: public class B{};
A是B的直接基类
A是C的间接基类

Example

#if 1
#include <iostream>
using namespace std;

class A
{
private:
	int pri;	//私有的属性,会被继承,但是不能访问
protected:
	int pro;
public:
	int pub;
	A()
	{
		cout << "A的构造函数" << endl;
	}
	~A()
	{
		cout << "A的析构函数" << endl;
	}
};

class AA
{
private:
	int pri;	//私有的属性,会被继承,但是不能访问
protected:
	int pro;
public:
	int pub;
};
//以私有的方式继承父类,继承过来的属性都是私有的
class B :private A
{
public:
	void fun()
	{
		//cout << pri << endl;	//不能访问私有成员(有继承过来)
		cout << pro << endl;	
		cout << pub << endl;
	}

};




//以保护的的方式继承父类,继承过来的属性都是保护的
class C :protected A
{
	void fun()
	{
		//cout << pri << endl;	//不能访问私有成员(有继承过来)
		cout << pro << endl;
		cout << pub << endl;
	}
};
//以公有的方式继承父类,继承过来的属性都是
class D : public A
{
public:
	void fun()
	{
		//cout << pri << endl;	//不能访问私有成员(有继承过来)
		cout << pro << endl;
		cout << pub << endl;
	}

	D()
	{
		cout << "D的构造函数" << endl;
	}
	~D()
	{
		cout << "D的析构函数" << endl;
	}
};

class E : public B
{
	void fun()
	{
		//cout << pri << endl;	//不能访问私有成员(有继承过来)
		//cout << pro << endl;
		//cout << pub << endl;
	}
};

class F :public A, public AA
{
	void fun()
	{
		//cout << pri << endl;	//不能访问私有成员(有继承过来)
		cout << A::pro << endl;
		cout << AA::pub << endl;
	}
};




int main()
{
/*
	B b;
	cout << b.pro << endl;
	cout << b.pub << endl;
*/
/*
	C c;
	cout << c.pro << endl;
	cout << c.pub << endl;
*/

	D d;
	//cout << d.pro << endl;
	cout << d.pub << endl;

/*
	E e;
*/
	return 0;
}
#endif

类成员访问规则

在这里插入图片描述

继承类型

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值