用途:
在全局程序域类使用某一类型对象(基类 Base Class), 一般不实例化基类,
而是实例化基类的派生类,
在全局程序内我们只关心这类对象的行为(基类中的虚函数),而不关心
其具体实现(在派生类中override 基类的方法)
最后,释放为派生类分配的存储空间。
Example Code:
class Base
{
public:
Base();
virtual ~Base(); //attention keyword virtual,
//only declare as virtual, when delelte pBase
// can call pDerive->~Derive(), and free the space allocate for object of derive class.
public:
virtual int method1();
virtual int method2();
.
.
.
private:
int var;
.
.
};
class Dervie : public Derive
{
public:
Dervie ();
virtual ~Dervie (); //attention keyword virtual,
//only declare as virtual, when delelte pBase
// can call pDerive->~Derive(), and free the space allocate for object of derive class.
public:
int method1();
int method2();
.
.
.
};
void func(Base **ppBase)
{
*ppBase=new Derive;
}
int main()
{
Base *pBase;
func(&pBase);
delete pBase;
return 0;
}
本文介绍C++中如何通过虚析构函数支持基类指针删除派生类对象,实现多态行为。主要讲解了基类与派生类的定义、构造与析构过程,以及通过基类指针操作派生类对象的内存管理。
5979

被折叠的 条评论
为什么被折叠?



