堆栈损坏,不会返回

时间:2014-02-09 18:43:14

标签: c++ stack overloading

我创建了自己的堆栈和重载函数。然而,当我调用函数时,返回堆栈被破坏,我无法弄清楚原因:/我是c ++的新手并且很想学习!这是我的代码

主要

int main(){
string line;
SStack s1(1000);
SStack s2(1000);
int cap = s1.getCapacity();
cout << "Is the stack empty? " << s1.IsEmpty() << "\n";
cout << "The capacity of the stack is: " << cap << "\n";
ifstream myfile("all.last.txt");
cout << "s1 begin pushing: \n";
for (int i = 0; i <= 500; i++){
    getline(myfile, line);
    cout << "Pushing " << line << "\n";
    s1.push(line);
}
cout << "s2 begin pushing: \n";
for (int i = 0; i <= 50; i++){
    getline(myfile, line);
    cout << "Pushing " << line << "\n";
    s2.push(line);
}
myfile.close();
cout << "Is the stack empty? " << s1.IsEmpty() << "\n";
string top = s1.top();
cout << "The top object on the stack is: " << top << "\n";
cout << "The size of the stack is: " << s1.size() << "\n";
cout << "Popping: " << s1.pop() << "\n";
cout << "Size after pop is: " << s1.size() << "\n";
s1 = s1 + s2;
cout << s1.top();

}

不返回的SStack功能

    SStack::SStack(const SStack& s) : used(-1), Capacity(0), DynamicStack(0){
    *this = s;
}

SStack SStack::operator=(const SStack& s){
    if (this != &s){
        int cap = s.getCapacity();
        DynamicStack = new string[cap];
        Capacity = cap;
        used = -1;
        for (int count = 0; count < s.size(); count++){
            DynamicStack[count] = s.DynamicStack[count];
            used++;
        }
        }
        return *this;
}

SStack SStack::operator +(const SStack& s2){
int size1 = used + 1;
int size2 = s2.size();
SStack result = *this;
if (size1 + size2 <= Capacity){
    for (int count = 0; count < s2.size(); count++){
        result.push(s2.DynamicStack[count]);
    }
    return result;
}
else{
    cout << "Error stack is not big enough";
    return result;
}

1 个答案:

答案 0 :(得分:0)

您在2个位置分配堆栈实例,但我没有看到operator = definition。 我建议你在你的SStack类中添加一个operator =(),并将你的拷贝构造函数委托给这个operator =()。确保您的operator =()检查它是否在复制自己:

...
SStack::SStack(const SStack &s) : used(-1), Capacity(0), DynamicStack(0)
{ 
    *this = s; 
}
SStack &SStack::operator=(const SStack &s)
{
    if (this != &s && s.size() > 0)
    {
        // check if we already have an allocated array
        if (Capacity < s.size())
        {
            // safe even if Capacity==0 as long as DynamicStack==0 too
            delete [] DynamicStack;  

            int cap = s.getCapacity();
            DynamicStack = new string[cap];
            Capacity = cap;
        }
        used = -1;
        for (int count = 0; count < s.size(); count++){
            DynamicStack[count] = s.DynamicStack[count];
            used++;
        }
    }
    return *this;
}

尝试使用degugger,我建议您重新检查“used”变量,以确保它在所有使用的地方确实具有您想要的索引。

希望这有帮助。