概述
当我们在定义类的时候类与类之间可能存在某些共性这些共性是可以通过继承被传承给下一个类的,我们将其称为继承,使用其技术可以减少重复的代码,提高类之间的关系性
继承的基本语法
语法格式: class 子类 : 继承方式 父类 {}
class BaseClass {
public:
init() { cout<<"初始化"<<endl; }
}
class MyClas : public BaseClass {
public:
say(){ cout<<"我是子类"<<endl; }
}
继承方式
继承方式一共有三种:
- public:公共继承
- public:私有继承
- protected:保护继承
— | public成员 | private成员 | protected成员 |
---|---|---|---|
公共继承 | 继承后为public成员 | 继承后内外不可访问 | 继承后为protected成员 |
私有继承 | 继承后为private成员 | 继承后内外不可访问 | 继承后为private成员 |
保护继承 | 继承后为protected成员 | 城后内外不可访问 | 继承后为protected成员 |