C++网易云课堂开发工程师--虚函数与多态

时间:2021-01-22 21:55:00

Inheritance(继承),表示is-a

non-virtual 函数:不希望derived class 重新定义(override,复写)

virtual函数:希望derived class重新定义它(override,复写)它,并且它已经有默认定义。

pure-virtual函数(纯虚函数):希望derived class一定要重新定义(override)它,你对它没有默认定义。

class Shape{

  public:

    virtual void draw() const = 0;                        //纯虚函数

    virtual void error(const std::string& msg);

    int objectID() const;  

};

 

class Rectangle: public Shape{...};

class Ellipse: public Shape{...};

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Inheritance(继承) with virtual

Template Method 模板方法模式

Application framework                               Application

CDocument::OnFileOpen( ){                        class CMyDoc:  public CDocument{

  serialize( );                                  virtual Serialize( )  {...}

}                                    };

                                     main( ){

                                        CMyDoc myDoc;

                                        ...

                                        myDoc.OnFileOpen( );

                                     }

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#include<iostream>

using namespace std;

 

class CDocument{

  public:

    void OnFileOpen( ){

    //这是一个算法,每个cout输出代表一个实际动作

    cout << "dialog..." << endl;

    cout << "check file status ..." << endl;

    Serialize( );

    cout << "close file ..." << endl;

  }

  virtual void Serialize( )  { };

};

 

class CMyDoc : public CDocument{

  public:

    virtual void Serialize ( ){

    //只有应用程序本身才知道如何读取自己的文件

    cout << "重写虚函数" << endl;

  }

};

 

int main( ){

  CMyDoc myDoc( );

  myDoc.OnFile( );

}

继承与复合关系下的构造和析构

 

 

委托+继承

class Subject{

  int m_value;

  vector<Observer*>  m_views;

  public:

    void attach(Observer* obs){

      m_views.push_back(obs);

    }

    void set_val(int value){

      m_value = value;

      notify( );

    }

    void notify( ){

      for(int i = 0; i < m_views.size( ); ++i){

        m_views[i]->update(this, m_value);

      }

    }

}

Observer

class Observer{

  public:

    virtual void update(object* sub, int value);

}