C++ virtual function and polymorphism

For the inheritance of different data
1. For values, inherit the parent class
2. For functions, inherit the right to call

The type of virtual function
non-virtual function: do not want the derived class (subclass) to be overridden
virtual function: hope that the subclass overrides the function, and there is a default definition
pure virtual: the function override has not been defined at all, and the subclass must be defined

class Shape{
    
    
public:
    virtual void draw() const = 0;//pure virtual 
    virtual void error(const std::string& msg);//impure virtual
    int objectID() const;//non-virtual
    ...
};

class Rectangle : public Shape{
    
    ...};
class Elipse : public Shape{
    
    ...};

Template Method
insert image description here
calls the function of the parent class through the subclass object

Execution sequence:
execute sequentially in the main function, then go to CDocument::OnFileOpen(), continue to the Serialize virtual function, because this is a virtual function, then go to the specific Serialize implementation, and finally return to myDoc.OnFileOpen()
CDocument ::OnFileOpen(&myDoc)
this->Serialize()//The this pointer here is the passed &myDoc

#include <iostream>
using namespace std;
class CDocument
{
    
    
public:
    void OnFileOpen()
    {
    
    
        //这是个算法
        Serialize();
    }
    virtual void Serialize();
};
class CMyDoc : public CDocument
{
    
    
public:
    virtual void Serialize()
    {
    
    
        //只有应用程序本身才知道如何读取自己的格式
          cout<<"CMyDoc::Serialize()"<<endl;  
    }
}
int main()
{
    
    
    CMyDoc myDoc;
    myDoc.OnFileOpen();
}

– Learned from Mr. Hou Jie

Guess you like

Origin blog.csdn.net/weixin_43367756/article/details/125881447