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

*/

沒有留言:

2024年React state management趨勢

輕量化 在過去Redux 是 React 狀態管理的首選函式庫。 Redux 提供了強大的功能和靈活性,但也帶來了一定的學習成本和複雜度。 隨著 React 生態的不斷發展,越來越多的開發者開始追求輕量化的狀態管理函式庫。 Zustand 和 Recoil 等庫以其簡單易用、性...