代码如下,学习C++的时候写的,在运行到abc.push(a)的时候崩溃了,请问有可能是什么原因?
#include
#include
#include
#include
using namespace std;
template
class stack{
private:
int maxSize;
int size;
int top;
type* content;
public:
stack();
bool isEmpty();
bool isFull();
bool push(const type & item);
bool pop(type& item);
virtual ~stack();
};
template
stack::stack(){
top = 0;
size = 0;
maxSize = 10;
type* content = new type10;
}
template
stack::~stack(){
delete [] content;
}
template
bool stack::isEmpty(){
return top == 0;
}
template
bool stack::isFull(){
return top == maxSize;
}
template
bool stack::push(const type& item){
if(this->isFull()){
return false;
}else{
content[top++] = item;
return true;
}
}
template
bool stack::pop(type& item){
if(this->isEmpty()){
return false;
}else{
item = content[--top];
return true;
}
}
int main(void){
stack abc;
string a = "abcdefg";
abc.push(a);
cout << abc.isEmpty() << endl;
cout << abc.isFull() << endl;
return 0;
}
你这复制出来的代码应该不全,都是你自己写的,单步调试看看
大概看了一下你的代码,你的count是一个指针,如果你想push一个长度大于1的string,必须要在构造函数用new分配内存,不然程序会挂掉。
兄弟,
stack::stack()
{
top = 0;
size = 0;
maxSize = 10;
type* content = new type[10];
}
这个type* content = new type[10];
你是重新定义了一个新变量type*content 然后把用这个新变量申请了动态内存
而这个新变量的生存期也只在构造函数结束后就没了
你在类里面定义的哪个type*content却傻愣的什么事也没被做,还是一指针
然后你又在push函数里面把这个连初始化都没有做过的指针当做数组用,嗯哼?
正确做法是把type* content = new type[10];这句里的type*去掉
因为
您已经定义过他了呀
哥们儿代码贴的不全啊,楼上说的的确是存在的一个问题,你已经定义了content指针了,构造函数里面又定义了一个content,根据作用域的原则,构造函数中的content只是局部的还用new申请的内存空间,你又没释放,这里面就有内存泄漏了。另外,你这个写的是模板类么?type类型是模板实参?如果是的话为什么stack没有指定模板实参呢?你的代码我拷出来是错误的
这种错误明显,单步调试下,你这代码贴出来也无法看清