您不应该删除void
指针。delete
适用于特定类型(如编译器知道,应该调用哪个析构函数 - 如错误消息中所述)。
如果你想在你的结构中保存未指定的类型,你必须以某种方式包装它。
class DataWrapper
{
public:
virtual void * GetData() = 0;
virtual ~DataWrapper()
{
}
};
class MyDataWrapper
{
protected:
MyData * data;
public:
MyDataWrapper(MyData * newData)
{
data = newData;
}
void * GetData()
{
return data;
}
~MyDataWrapper()
{
delete data;
}
};
struct vStruct
{
MyDataWrapper * vPtr;
struct vStruct *next;
~vStruct()
{
if (vPtr != null)
delete vPtr;
}
};
vStruct sObj;
sObj.vPtr = new MyDataWrapper(new MyData());
// When sObj gets deleted, MyDataWrapper is
// deleted too (thanks to the ~vStruct) and
// in effect, the allocated data is deleted too.
请注意,这是一个简单的示例,可以更美观地编写。