cga*_*gao 1 c++ char virtual-destructor
我是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;
}
Run Code Online (Sandbox Code Playgroud)
要么
int main(){
Parent *a = new Child("Tom");
delete a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
两者都会给出Debug Assertion Failed的错误窗口.
对于这种情况,我应该如何正确编写虚拟析构函数?
非常感谢
因为您尝试删除文字字符串指针.您将Child::name成员设置为指向文字字符串"Tom",该字符串是指向编译器创建的内存的指针.你应该只delete明确你的意思new.
另请注意,每个Parent和Child类都有不同且不同的name成员变量.初始化Child::name变量时,其中的变量Parent仍未初始化.