用于将类的每个实例添加到列表对象的构造方法

时间:2017-01-13 21:58:59

标签: c++ list oop constructor

c ++和OOP的新手。我正在尝试找出列表和迭代,所以我创建了以下示例代码。我创建了一些Thing对象,但是我想确保在创建Thing时,它的构造函数将它添加到列表“things”(在lists对象中),以便我可以跟踪Thing的每个实例。在main()的底部,然后我遍历事物列表。有没有更好的方法来做到这一点,或者你能指出如何在我的Thing构造函数中做到这一点?谢谢!

#include <iostream>
#include <list>

class Thing;

class Lists
{
public:
    std::list<Thing> things;
    Lists() {
        std::cout << "List object with list 'things' created" << std::endl;
    }
};

class Thing
{
public:
    int howMuch, pointer;
    Thing(int x, Lists* y)
    {
        howMuch = x;
        y->things.push_back(this);
    }
};

int main()
{

    //create the object that holds the list of things
    Lists lists;

    //make some objects, and pass a pointer of the lists to the constructor
    Thing thingA(123, &lists);
    Thing thingB(456, &lists);

    for (std::list<Thing>::iterator it = lists.things.begin(); it != lists.things.end(); ++it)
        std::cout << "test" << it->howMuch << std::endl;

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您可以使用静态字段_things:

将创建的项目存储在Thing类本身中
#include <iostream>
#include <list>

class Thing
{
    static std::list<Thing> _things;

public:
    int howMuch, pointer;
    Thing(int x) : howMuch(x)
    {
        _things.push_back(*this);
    }

    static std::list<Thing> getAllThings()
    {
        return _things;
    }
};


std::list<Thing> Thing::_things;

int main()
{
    Thing thingA(123);
    Thing thingB(456);

    auto allThings = Thing::getAllThings();

    for (auto it = allThings.begin(); it != allThings.end(); ++it)
        std::cout << "test " << it->howMuch << std::endl;

    return 0;
}