1 概述
继承是面型对象的三大特征之一
继承用于描述类于类之间的从属关系,被继承的类称为基类或父类,继承的类称为子类
2 继承的基本语法
#include <iostream>
using namespace std;
class Father {
public:
int getNum() {
return m_num;
}
public:
int m_num = 10;
};
class Son :public Father {
};
int main() {
Son son;
cout << son.m_num << endl;
cout << son.getNum() << endl;
return 0;
}
输出
10
10
继承之后,子类拥有了父类的属性和行为。需要注意的是,子类是否拥有父类的属性和行为,还决定于继承方式和父类的访问权限。
3 继承方式
继承访问分为三种
- 公共继承
- 保护继承
- 私有继承
语法
class 子类 :继承方式 父类
#include <iostream>
using namespace std;
class Father {
private:
int m_A;
protected:
int m_B;
public:
int m_C;
};
void test() {
Father father;
// father.m_A; //不能访问private成员
// father.m_B; //不能访问protected成员
father.m_C;
}
// 公共继承
class Son1 : public Father {
public:
void func() {
// m_A; //不可访问private成员
m_B;
m_C;
}
};
void test1() {
Son1 son;
// son.m_A; //不可访问private成员
// son.m_B; //不可访问protected成员
son.m_C;
}
// 保护继承
class Son2 : protected Father {
public:
void func() {
// m_A; //不可访问private成员
m_B;
m_C;
}
};
void test2(