2010/03/21

[C++] Virtual Destructor

#include <iostream>

#include <string>

#include <vector>

using namespace std;

/*

             1    *
Human -----> Tool
                        /\ 
                        |
                     |-----| 
                     |      |
                Pen   Pencil

*/

class Tool // the abstract class

{

public:

// no explicit constructor. there is a default one - Tool();

virtual void use() = 0;

virtual ~Tool(){

cout << "calling ~Tool()" << endl;

}

};

class Pen: public Tool

{

private:

int *x; // some private data;

public:

Pen(){

x = new int[100];

}

void use(){

    cout << "using the Pen" << endl;

}

~Pen(){

cout << "calling ~Pen()" << endl;

delete [] x; // x is a pointer to dynamically allocated memory space in this object. Pencil is responsible to delete the space.

}

};

class Pencil: public Tool

{

private:

char *y; // some private data;

public:

Pencil(){

y = new char[100];

}

void use(){

cout << "using the Pencil" << endl;

}

~Pencil(){

cout << "calling ~Pencil()" << endl;

delete [] y; // y is a pointer to dynamically allocated memory space in this object. Pencil is responsible to delete the space.

}

};

class Human

{

private:

vector<Tool*> tools;

public:

void addTool(Tool* tool){ // keep the pointers to Tools only.

tools.push_back(tool);

}

void paint() // use each tool

{

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

tools[i]->use();

}

}

virtual ~Human()

{

cout << "Calling ~Human()" << endl;

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

delete tools[i]; // if the tools are not shared between other Human, this Human object should delete the tools.

}

}

};

int main()

{

Human *human = new Human();

human->addTool(new Pen());

human->addTool(new Pen());

human->addTool(new Pencil());

human->paint();

delete human;

return 0;

}

/* output:

using the Pen

using the Pen

using the Pencil

Calling ~Human()

calling ~Pen()

calling ~Tool()

calling ~Pen()

calling ~Tool()

calling ~Pencil()

calling ~Tool()

*/

沒有留言:

4種PDF轉Word的免費方法(pdf to word, pdf to doc, pdf2word, pdf2doc)

本文將介紹4種 將PDF轉Word檔 的方法,分別分析其效能、方便性、精確性等指標。 1. nitropdf提供的線上 Convert PDF to Word (DOC) 這是一個 線上免費PDF轉Word檔 的服務,網址: http://www.pdftoword.com...