9.6.7 虚析构函数(1)
当使用基类指针处理派生类对象时,出现的一个问题是正确的析构函数可能没有被调用。通过修改上一个示例,我们就能看到这样的结果。
试一试:调用错误的析构函数
在本示例中,我们只需给每个类添加一个输出消息的析构函数,以便了解销毁对象时被调用的是哪一个析构函数。该示例的Container.h文件如下所示:
- // Container.h for Ex9_12
- #pragma once
- #include <iostream>
- using std::cout;
- using std::endl;
-
- class CContainer // Generic base class for specific containers
- {
- public:
- // Destructor
- ~CContainer()
- { cout << "CContainer destructor called" << endl; }
-
- // Function for calculating a volume - no content
- // This is defined as a 'pure' virtual function, signified by '= 0'
- virtual double Volume() const = 0;
-
- // Function to display a volume
- virtual void ShowVolume() const
- {
- cout << endl
- << "Volume is " << Volume();
- }
- };
该示例的Can.h文件内容如下:
- // Can.h for Ex9_12
- #pragma once
- #include "Container.h" // For CContainer definition
- extern const double PI;
-
- class CCan: public CContainer
- {
- public:
- // Destructor
- ~CCan()
- { cout << "CCan destructor called" << endl; }
-
- // Function to calculate the volume of a can
- virtual double Volume() const
- { return 0.25*PI*m_Diameter*m_Diameter*m_Height; }
-
- // Constructor
- CCan(double hv = 4.0, double dv = 2.0): m_Height(hv), m_Diameter(dv){}
-
- protected:
- double m_Height;
- double m_Diameter;
- };
Box.h文件的内容应该是:
- // Box.h for Ex9_12
- #pragma once
- #include "Container.h" // For CContainer definition
- #include <iostream>
- using std::cout;
- using std::endl;
-
- class CBox: public CContainer // Derived class
- {
- public:
- // Destructor
- ~CBox()
- { cout << "CBox destructor called" << endl; }
-
- // Function to show the volume of an object
- virtual void ShowVolume() const
- {
- cout << endl
- << "CBox usable volume is " << Volume();
- }
-
- // Function to calculate the volume of a CBox object
- virtual double Volume() const
- { return m_Length*m_Width*m_Height; }
-
- // Constructor
- CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0)
- :m_Length(lv), m_Width(wv), m_Height(hv){}
-
- protected:
- double m_Length;
- double m_Width;
- double m_Height;
- };
GlassBox.h头文件应该包含下面的代码:
- // GlassBox.h for Ex9_12
- #pragma once
- #include "Box.h" // For CBox
-
- class CGlassBox: public CBox // Derived class
- {
- public:
- // Destructor
- ~CGlassBox()
- { cout << "CGlassBox destructor called" << endl; }
-
- // Function to calculate volume of a CGlassBox
- // allowing 15% for packing
- virtual double Volume() const
- { return 0.85*m_Length*m_Width*m_Height; }
-
- // Constructor
- CGlassBox(double lv, double wv, double hv): CBox(lv, wv, hv){}
- };