如何删除基类指针? [英] How to delete the Base class pointer?

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

问题描述

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

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.

推荐答案

虚拟析构函数将是一个好主意,但您的主要示例不需要任何删除!,因为在堆栈上实例化了obj_Derived.

将示例更改为

Virtual destructor would be a good idea, BUT your main example does NOT need any delete!, cause obj_Derived is instanciated on stack.

When changing the example to

int main()
{
  Interface *pInterface;

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

  delete pInterface;
  return 0;
}



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



THEN the virtual destructor will do the job.


您猜对了:
You guessed correctly:
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.


//我想删除 pInterface
/> 为什么 ?没有了...:)
// I want to delete the pInterface
Why ? There was no new for it... :)


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆