几行程序,delete父类指针,导致崩溃,为什么?
我用VC2005新建一个控制台工程,什么编译选项也没有改:
- C/C++ code
class father{ int i;public: void f(){printf("father\n");} virtual ~father(){}//我已经把父类的dtor指定为虚函数了呀};class child{public: virtual void f(){printf("child\n");}}; int _tmain(int argc, _TCHAR* argv[]){ father* pf=(father*)(new child); child* pc=dynamic_cast<child*>(pf);//如果我想关掉/GR,VC2005/2010用什么编译选项? delete pf;//导致运行时错误,为什么? return 0;}网上说,vc2005默认是打开rtti生成的。这个编译选项在vc6里面是/GR,vc2005/2010下面叫什么? 我在工程属性-->命令行下面没有看到有叫做/GR的选项。
我的父类里面,析构函数已经声明为了virtual。我发现我的程序是在delete pf这一行奔溃的。去掉这一行就没有事了。
为什么呢?
[解决办法]
我知道你的意思
但是你的代码明显错了
child应该是派生自father类吧?
不然的话:father* pf=(father*)(new child);怎么能转换?
所以你的child类写错了,这样改下:
- C/C++ code
#include "stdafx.h"class father{ int i;public: void f(){printf("father\n");} virtual ~father(){}//我已经把父类的dtor指定为虚函数了呀};class child:public father//child继承father类{public: virtual void f(){printf("child\n");}}; int _tmain(int argc, _TCHAR* argv[]){ father* pf=(father*)(new child); pf->f(); child* pc=dynamic_cast<child*>(pf);//如果我想关掉/GR,VC2005/2010用什么编译选项? pc->f(); delete pf;//导致运行时错误,为什么? return 0;}