【C++语法实践】11-C++ 纯虚函数

#include <iostream>
#include <vector>

using namespace std;

// 拥有一个或多个纯虚函数的类,称为抽象类
// 抽象类应该将析构函数定义为虚函数,这样在delete抽象类指针的时候,
// 派生类和抽象类的析构函数才能都被调用
class Shap
{
public:
    virtual void Draw() = 0;
    virtual ~Shap() {}
};

class Circle : public Shap
{
public:
    void Draw()
    {
        cout << "Circle Draw ..." << endl;
    }

    ~Circle()
    {
        cout << "Circle Destructor" << endl;
    }
};

class Square : public Shap
{
public:
    void Draw()
    {
        cout << "Square Draw ..." << endl;
    }

    ~Square()
    {
        cout << "Square Destructor" << endl;
    }
};

void DrawAllShap(const vector<Shap*>& vecShap)
{
    vector<Shap*>::const_iterator it;
    for (it = vecShap.begin(); it != vecShap.end(); ++it)
        (*it)->Draw();
}

void DeleteAllShap(const vector<Shap*>& vecShap)
{
    vector<Shap*>::const_iterator it;
    for (it = vecShap.begin(); it != vecShap.end(); ++it)
        delete(*it);
}

int main()
{
    // Shap shap; // 不能实例化抽象类
    vector<Shap*> vecShap;
    Shap* shap;

    shap = new Circle;
    vecShap.push_back(shap);
    shap = new Square;
    vecShap.push_back(shap);

    DrawAllShap(vecShap);
    DeleteAllShap(vecShap);

    return 0;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部