我是 C++ 的新手,正在学习虚函数,并且知道如果类具有虚函数并且类具有指针成员,则必须编写虚析构函数。下面是我的代码,我使用的是 Virtual Studio 2013RC
#include<iostream>
using namespace std;
//base and derived class with virtual function
class Parent{
protected:
const char *name;
public:
virtual void say(){ cout << "1" << endl; }
virtual void showName(){ cout << name << endl; }
Parent(){};
Parent(const char *myName) :name(myName){};
virtual ~Parent(){ delete name; cout << "Parent name deleted" << endl; }
};
class Child :public Parent{
protected:
const char *name;
public:
virtual void say(){ cout << "2" << endl; }
virtual void showName(){ cout << name << endl; }
Child(){};
Child(const char *myName) :name(myName){};
virtual ~Child(){ delete name; cout << "Child name deleted" << endl;}
};
int main(){
Child a("Tom");
return 0;
}
或者
int main(){
Parent *a = new Child("Tom");
delete a;
return 0;
}
两者都会给出调试断言失败的错误窗口。
对于这种情况,应该如何正确编写虚拟析构函数?
非常感谢
最佳答案
因为你试图删除一个文字字符串指针。您将 Child::name
成员设置为指向文字字符串 "Tom"
,这是一个指向编译器创建的内存的指针。您应该只删除
您明确新建
的内容。
另请注意,Parent
和Child
类各有不同且截然不同的name
成员变量。当您初始化 Child::name
变量时,Parent
中的变量仍未初始化。
关于c++ - 当我尝试删除 char* 时调试断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20934079/