如何删除基类指针

如何删除基类指针

本文介绍了如何删除基类指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的完整代码.......

This is mine whole code.......

class Interface
{
public:
virtual void fun()=0;
};
class Derived:public Interface
{
public:
void fun()
{
printf("i am in derived class fun\n");
}
};

int main()
{
Interface *pInterface;
Derived obj_Derived;

pInterface=&obj_Derived;

pInterface->fun();


return 0;
}





我想删除





I want to delete the

pInterface pointer

,因此我可以调用

delete pInterface; 

否则我应该在Interface类中使用虚拟析构函数.

or should i have to take virtual destructor in Interface class.

推荐答案

int main()
{
  Interface *pInterface;

  pInterface=new Derived();
  pInterface->fun();

  delete pInterface;
  return 0;
}



然后,虚拟析构函数将完成这项工作.



THEN the virtual destructor will do the job.


delete pInterface;


将不会执行此操作,因为编译器不知道该对象将要删除哪个对象.因此,在您的接口类中声明一个虚拟析构函数,一切都会好起来.


will not do the job, because the compiler has no idea about which object is going to be deleted by this. So declare a virtual destructor in your interface class and all will be fine.



这篇关于如何删除基类指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 00:33