藏經閣

一切有為法,如夢幻泡影,如露亦如電,應作如是觀。

#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()

*/

如何在Blogger新增隨機文章

Blogger Hack - How to add a Random Post Gadget in Blogger)

 


0 意見

張貼留言

Archives