c++ - 将类的每个实例添加到列表对象的构造函数

标签 c++ list oop constructor

C++ 和 OOP 新手。我正在尝试找出列表和迭代,因此我创建了以下示例代码。我创建了几个 Thing 对象,但我想确保在创建 Thing 时,其构造函数将其添加到列表“things”(在列表对象内),以便我可以跟踪 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;
}

最佳答案

您可以使用静态字段 _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;
}

关于c++ - 将类的每个实例添加到列表对象的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41644086/

相关文章:

jquery - 一个搜索列表,根据受欢迎程度以不同的边框宽度 float

c++ - 我的VSCode调试器未显示任何变量值(附加图像)(C++)

用于简单类序列化的 C++/sqlite 包装器?

python - 这些函数名称中的点是什么原因造成的

c++ - 使用模板时获取 "Trigger Breakpoint Error at delete"

c++ - 制作复制构造函数

javascript - 为什么在声明子类时我的 Javascript 父作用域被覆盖?

java - 能否在 C/C++ 中提取 Java ZipEntry

python - 从 Python 中的元组列表中获取配对元素

python - Pandas DataFrame 创建一个包含列表的列