一、定义
- non-virtual函数:你不希望derived class重新定义(override,覆盖)它
- virtual函数:你希望derived class重新定义(override,覆盖)它,且已有默认定义
- pure virtual函数:你希望derived class重新定义(override,覆盖)它,对它没有默认定义
二、例子1
class Shape {
public:
virtual void draw() const = 0; // pure virtual
virtual void error(const std::string& msg); // virtual
int objectID() const; // non-virtual
...
};
class Rectangle:public Shape{...};
class Ellipse:public Shape{...};
三、经典用法(Template Method)
四、例子2
#include <iostream>
using namespace std;
class CDocument
{
public:
void OnFileOpen()
{
// 这表示一个算法,每个count输出代表一个实际动作
cout<<"dialog..."<<endl;
cout<<"check file status..."<<endl;
cout<<"open file..."<<endl;
Serialize();
cout<<"close file..."<<endl;
cout<<"update all views..."<<endl;
}
virtual void Serialize() { };
};
class CMDoc : public CDocument
{
public:
virtual void Serialize()
{
cout<<"CMDoc::Serialize()"<<endl;
}
};
int main()
{
CMDoc mydoc;
mydoc.OnFileOpen();
}