gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:50:00 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com