C ++ - List没有保留其元素

时间:2018-04-11 15:42:41

标签: c++ list

我有两节课; TestUnit和TestShot。 TestUnit需要保存一个TestShots列表,但是当我稍后在列表中引用我已经给出的所有元素时,它已经消失了!

TestUnit.h

#include <string>
#include <list>
#include "TestShot.h"

using namespace std;

class TestUnit
{
public:
    TestUnit(string);
    string getName(void);
    void addShot(TestShot);
    list<TestShot> getShots(void);

    bool operator == (const TestUnit& tu) const { return name == tu.name; }
    bool operator != (const TestUnit& tu) const { return !operator==(tu); }

private:
    string name;
    list<TestShot> shots;
};

TestUnit.cpp

#include "TestUnit.h"

TestUnit::TestUnit(string name)
{
    this->name = name;
}

string TestUnit::getName(void)
{
    return name;
}

void TestUnit::addShot(TestShot shot)
{
    shots.push_front(shot);
}

list<TestShot> TestUnit::getShots(void)
{
    return shots;
}

TestShot.h

#include <string>

using namespace std;

class TestShot
{
public:
    TestShot(string);
    string getName(void);

private:
    string name;
};

TestShot.cpp

#include "TestShot.h"

TestShot::TestShot(string name)
{
    this->name = name;
}

string TestShot::getName(void)
{
    return name;
}

主要

#include <string>

#include "exports.h"
#include "TestUnit.h"

using namespace std;

// Global Variables
list<TestUnit> testUnits;


int main()
{
    int nShots1 = 0;
    int nShots2 = 0;

    // Create Unit
    TestUnit *testUnit = new TestUnit("Name");
    testUnits.push_front(*testUnit);

    // Create Shot and add to Unit with same 'name'
    TestShot *testShot = new TestShot("Name");
    for (TestUnit unit : testUnits)
    {
        if (unit.getName() == (*testShot).getName())
        {
            unit.addShot(*testShot);
            nShots1 = unit.getShots().size();
        }
    }

    // Display number of Shots for each Unit
    for (TestUnit unit : testUnits)
    {
        nShots2 = unit.getShots().size();

        std::cout << nShots1 << ", " << nShots2 << std::endl;
    }


    system("PAUSE");
};

输出:

1, 0

因此列表意识到它在添加之后已经被直接填充,但是当我需要使用它时它就是空的。 我猜这是一个范围问题,但我似乎无法弄明白。 非常感谢所有帮助!

1 个答案:

答案 0 :(得分:2)

在您的每个for循环中,您通过访问list元素,因此您可以有效地复制{{1}中的内容修改它,然后销毁它。将循环更改为如下所示:

list

由于您使用的是C ++ 11或更高版本,因此您也可以使用for (TestUnit &unit : testUnits) { if (unit.getName() == (*testShot).getName()) { unit.addShot(*testShot); nShots1 = unit.getShots().size(); } } 代替显式输入(例如auto)。