我有以下代码:C++删除派生类被分配给所述基类的指针的指针
/* Example OOPBEI03.CPP */
#include <iostream>
using namespace std;
typedef char item;
class stack
{
private:
int p;
protected:
item *st;
public:
stack(int m=100)
{
st = new item[m];
p = 0;
}
~stack()
{
delete [] st;
}
void push(item v)
{
st[p++] = v;
}
item pop()
{
return st[--p];
}
int empty()
{
return !p;
}
};
class queue : public stack
{
private:
int q;
item *qp;
public:
queue(int m=50):stack(m)
{
q = 0;
qp = st;
}
~queue()
{
delete qp;
}
item deque()
{
return qp[q++];
}
};
int main()
{
stack s(50);
queue q(20);
s.push('a');
q.push('b');
s.push('c');
q.push('d');
cout<<"pop "<<s.pop()<<endl;
cout<<"pop "<<s.pop()<<endl;
cout<<"deque "<<q.deque()<<endl;
cout<<"deque "<<q.deque()<<endl;
cout<<"empty queue? "<<q.empty()<<endl;
cout<<"empty stack? "<<s.empty()<<endl;
getchar();
return 0;
}
我在主()在Visual Studio以下错误的端部得到:“调试断言失败!... _BLOCK_TYPE_IS_VALID(pHead-> nBlockUse)“。
如果我在类队列或堆栈的析构函数中取消注释删除操作(我取消注释只有一个操作!),我没有问题。
我该如何解决这个问题?
被删除我没有看到三/五规则被人跟踪。 – chris 2013-03-15 11:31:58
首先阅读关于'虚拟'析构函数,然后讲述[三项规则](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29),最后想一想当你尝试释放指针两次。 – 2013-03-15 11:35:35
@all:谢谢你的回答。问题是,这个代码在我的学习书中。我现在在学校学习C++。 – 2013-03-15 20:58:11