了解如何删除新动态分配的变量

时间:2016-11-28 05:52:12

标签: c++

此代码用于模拟您从引擎开始的火车,您可以添加火车车厢,分离火车车厢和在火车车厢之间移动。我没有问题,但我在删除我在程序结束时添加列车时创建的所有新盒子时遇到问题。我希望我的所有新火车都能保留,直到用户退出。那时,我想删除所有新框。我怎么做?我尝试在我的班级添加一个析构函数,然后删除"删除;"并且"删除之前的;"但该程序有一个运行时错误。我是指针和动态内存的新手,我想知道如何做到这一点。非常感谢!

#include <iostream>
#include <string>

class train{
    public:
        train(string n);
        bool hasNext();
        bool hasPrevious();
        string getName();
        train* nextTrain();
        train* previousTrain();
        void add(string);
        void detach();
    private:
        string name;
        train* nextTrn;
        train* previousTrn;
};

void train::detach()
{
    if(previousTrn -> hasPrevious())
    {
        previousTrn = previousTrn -> previousTrn;
        delete previousTrn -> nextTrn;
        previousTrn -> nextTrn = this;
    }
    else
        delete previousTrn;
}

train::train(string n)
{
    name = n;
    nextTrn = NULL;
    previousTrn = NULL;
}

void train::add(string n)
{
    train* x = new train(n);
    if(hasPrevious())
    {
        x -> previousTrn = previousTrn;
        x -> previousTrn -> nextTrn = x;
    }
    previousTrn = x;
    x -> nextTrn = this;
}

train* train::nextTrain()
{
    return nextTrn;
}

train* train::previousTrain()
{
    return previousTrn;
}

bool train::hasNext()
{
    if(nextTrn != NULL)
        return true;
    else
        return false;
}

bool train::hasPrevious()
{
    if(previousTrn != NULL)
        return true;
    else
        return false;
}

string train::getName()
{
    return name;
}


int main()
{
    train engine = train("Engine");
    train* current = &engine;
    string choice;
    do
    {
        if(current -> hasNext())
        {
            cout << "Next train: " << current -> nextTrain() -> getName() << endl;
        }

        cout << "Current train: " << current -> getName() << endl;

        if(current -> hasPrevious())
        {
            cout << "Previous train: " << current -> previousTrain() -> getName() << endl;
        }

        cout << "Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, (d)etach a train, or (q)uit?\n";
        getline(cin,choice);

        if(tolower(choice[0]) == 'n' && current -> hasNext())
        {
            current = current -> nextTrain();
        }
        else if(tolower(choice[0]) == 'p' && current -> hasPrevious())
        {
            current = current -> previousTrain();
        }
        else if(tolower(choice[0]) == 'a')
        {
            cout << "Which train is this?\n";
            string name;
            getline(cin, name);
            current->add(name);
        }   
        else if(tolower(choice[0]) == 'd' && current -> hasPrevious())
        {
            current->detach();
        }           

    }while(tolower(choice[0]) != 'q');

    current = &engine;
    while(current -> hasPrevious())
    {
        current = current -> previousTrain();
        delete current -> nextTrain();
    }
    delete current;
}

0 个答案:

没有答案