继承
继承是允许重用现有类来构造新类的特性
优点:
代码的可重用性,重定义基类的成员函数,向派生类添加新成员
可分为:
单一继承、多级继承、多重继承、层次继承
继承的实现
派生类的声明必须指定基类的名称
派生类:访问控制权限说明符 基类
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