Inheritance(繼承),表示is-aios
non-virtual 函數:不但願derived class 從新定義(override,複寫)算法
virtual函數:但願derived class從新定義它(override,複寫)它,而且它已經有默認定義。ide
pure-virtual函數(純虛函數):但願derived class必定要從新定義(override)它,你對它沒有默認定義。函數
class Shape{this
public:spa
virtual void draw() const = 0; //純虛函數server
virtual void error(const std::string& msg);繼承
int objectID() const; ip
};string
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);
}