继承介绍

面向对象三大特性之一

单继承: class 子类:继承方式[默认:私有] 父类 多继承: class 子类:继承方式[默认:私有] 父类, 继承方式[默认:私有] 父类,...

title:Example1
```cpp
#include <iostream>
using namespace std;
 
class BaseClass
{
public:
    void topPage()
    {cout << "顶部页面" << endl;}
    void bottomPage()
    {cout << "底部页面" << endl;}
    void leftPage()
    {cout << "左侧页面" << endl;}
    void rightPage()
    {cout << "右侧页面" << endl;}
};
 
class Java:public BaseClass
{
    void centerPage()
    {cout << "Java页面" << endl;}
};
 
class Cpp:public BaseClass
{
    void centerPage()
    {cout << "Cpp页面" << endl;}
};
 
class Python:public BaseClass
{
    void centerPage()
    {cout << "Python页面" << endl;}
};
 
int main()
{
    Java java;
    Cpp cpp;
    Python python;
    java.centerPage();
    cpp.centerPage();
    python.centerPage();
    /*output:
    Java页面
    Cpp页面
    Python页面
    */
}
title:Example2
```cpp
#include <iostream>
using namespace std;
 
class Base1
{
    printHello(){cout << "Hello ";}
};
 
class Base2
{
    printfWorld(){cout << "World" << endl;}
};
 
class Son: public Base1, public Base2;
 
int main()
{
    Son son;
    son.printHello();
    son.printWorld();
    return 0;
}
/*output:
Hello World
*/

继承方式

继承方式图解

⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠

Text Elements

class A { public: int a; protected: int b; private: int c; };

class B:public A { public: int a; protected: int b; 不可访问: int c; };

公有继承

保护继承

class B:protected A { protected: int a; int b; 不可访问: int c; };

class B:private A { private: int a; int b; 不可访问: int c; };

私有继承

指向原始笔记的链接

继承中的对象模型

  • 子类会全部继承来自父类的对象,即使是私有的
  • 私有的成员只是被隐藏了,但还是会继承下去
```cpp
class Base
{
public:
    int m_A;
protected:
    int m_B;
private:
    int m_C;
};
 
class Son:public Base
{
public:
    int m_D;
};
 
int main()
{
    cout << sizeof(Son) << endl;
    //output:16
}

继承中的构造和析构

父类->子构->子析->父析

```cpp
class Base
{
    Base()
    {cout << "Base构造函数调用" << endl;}
    ~Base()
    {cout << "Base析构函数调用" << endl;}
};
 
class Son:public Base
{
    Son()
    {cout << "Son构造函数调用" << endl;}
    ~Son()
    {cout << "Son析构函数调用" << endl;}
};
 
int main()
{
    Son son;
    /*output:
    Base构造函数调用
    Son构造函数调用
    Son析构函数调用
    Base析构函数调用
    */
}

父类子类同名成员处理

名字屏蔽

同名静态成员处理

菱形继承问题

两个基类有同名成员

class A
{
public:
      int a;
      void display();
};
 
class B
{
public:
      int a;
      void display();
}; 
 
class C : public A, public B
{
public :
      int b;
      void show();
}; 
title:Error
collapse:open
 
```cpp
int main()
{
C c1;
c1.a=3;
c1.display();
}

解决方法一 加上作用域

title:Success
collapse:open
```cpp
int main()
{
C c1;
c1.A::a=3;
c1.A::display();
}

解决方法二

待补充

学习路径