- 继承可以减少重复的代码。
- 继承允许我们依据另一个类来定义一个类,这使得创建和维护一个应用程序变得更容易。
- 基类=父类,派生类=子类,派生类是在继承了基类的部分成员基础上,加上自己的成员而产生的类。
继承的语法
class 子类名 : 继承方式 父类名1 , 继承方式 父类名2 , .....
{派生类的成员
};
继承方式:
继承方式的特点
- 无论哪种继承方式,父类中的private成员在子类中均不可以访问。
- public继承中,父类中public和protected权限到子类中不变。
- protected继承中,父类中的public和protected权限到子类中变为protected。
- private继承中,父类中的public和protected权限到子类中变为private。
继承方式的举例
code:#include <iostream>using namespace std;class Father{public:int m_public_a=1;protected:int m_protected_a=11;private:int m_private_a=111;public:void show_info(){cout << "m_public_a: " << m_public_a << ", m_protected_a: " << m_protected_a << ", m_private_a: " << m_private_a << endl;}};class Son : public Father{public:void show_info_1(){m_public_a = 5;m_protected_a = 55;cout << "m_public_a: " << m_public_a << ", m_protected_a: " << m_protected_a << endl;}};void test01(){Son s1;s1.m_public_a = 3;s1.show_info_1();}void main(){ test01();system("pause");}
result:m_public_a: 5, m_protected_a: 55
code:#include <iostream>using namespace std;class Father{public:int m_public_a=1;protected:int m_protected_a=11;private:int m_private_a=111;public:void show_info(){cout << "m_public_a: " << m_public_a << ", m_protected_a: " << m_protected_a << ", m_private_a: " << m_private_a << endl;}};class Son: protected Father{public:void show_info_1(){m_public_a = 5;m_protected_a = 55;cout << "m_public_a: " << m_public_a << ", m_protected_a: " << m_protected_a << endl;}};void test01(){Son s1;s1.show_info_1();}void main(){ test01();system("pause");}
result:m_public_a: 5, m_protected_a: 55
code:#include <iostream>using namespace std;class Father{public:int m_public_a=1;protected:int m_protected_a=11;private:int m_private_a=111;public:void show_info(){cout << "m_public_a: " << m_public_a << ", m_protected_a: " << m_protected_a << ", m_private_a: " << m_private_a << endl;}};class Son: private Father{public:void show_info_1(){m_public_a = 5;m_protected_a = 55;cout << "m_public_a: " << m_public_a << ", m_protected_a: " << m_protected_a << endl;}};class Grandson: public Son{public:void show_info_1(){}};void test01(){Son s1;s1.show_info_1();}void main(){ test01();system("pause");}
result:m_public_a: 5, m_protected_a: 55