访问包含列表的对象列表的内容

Accessing the contents of a list of objects that contain a list

本文关键字:列表 对象 访问 包含      更新时间:2023-10-16

我已经试着让它工作了几个星期了。我很尴尬。我觉得答案可能简单得可笑。

我想定义一种包含列表的对象类型(即类(,例如类ListA{string category;list<string>components;…}。然后我想创建这些对象的列表,例如list<ListA>myMenu。正如你已经猜到的,我不能让它工作。

这是代码:

#include <iostream>
#include <list>
using namespace std;
class ListA {
public:
    string category;
    list<string> items;
    ListA() { category = "Unentitled"; }
    ListA(const ListA& orig){}
    ~ListA(){}
};
int main(int argc, char** argv) {
    cout<<"nnTEST a6.3: Let's try an example that is more complete. ";
    //setup lists for each entree
    ListA ingredientsA;
    ingredientsA.category="Pizza";
    ingredientsA.items.push_back("tomatos"); ingredientsA.items.push_back("garlic");
    ingredientsA.items.push_back("cheese"); ingredientsA.items.push_back("dough");
    ListA ingredientsB;
    ingredientsB.category="Milk shake";
    ingredientsB.items.push_back("milk"); ingredientsB.items.push_back("ice cream");
    ingredientsB.items.push_back("cocoa"); ingredientsB.items.push_back("whip cream");
    //verify contents of lists are correctly added
    cout<<"nTEST a.6.3.2[Category("<<ingredientsB.category<<")]";
    cout<<"nTEST a.6.3.4[Ingredient("<<ingredientsB.items.front()<<")]";
    //add to our list of entries
    list< ListA > dishes;
    dishes.push_back(ingredientsA);
    dishes.push_back(ingredientsB);
    //grab first entree in dishes list just added, what the heck?
    ListA tmpa = dishes.front();
    cout<<"nTEST a.6.3.5[Category("<<tmpa.category<<")]";
    cout<<"nTEST a.6.3.6[Ingred size("<<tmpa.items.size()<<")]n";
    //same with iterator
    list< ListA >::iterator itra = dishes.begin();
    cout<<"nTEST a.6.3.5[Category("<<itra->category<<")]";
    cout<<"nTEST a.6.3.6[Ingred size("<<itra->items.size()<<")]n";
    return 0;
}

输出:

TEST a6.3: Let's try an example that is more complete. 
TEST a.6.3.2[Category(Milk shake)]
TEST a.6.3.4[Ingredient(milk)]
TEST a.6.3.5[Category()]
TEST a.6.3.6[Ingred size(0)]
TEST a.6.3.5[Category()]
TEST a.6.3.6[Ingred size(0)]
RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms

我创建列表<ListA>,将ListA对象添加到其中,它们会立即尝试访问该列表的元素,但无法访问任何该死的东西。(参见a.6.3.5和.6;第一个是直接访问,第二个是使用迭代器。(

建议?我做错了什么傻事?

ListA(const ListA& orig){}

您的类有一个显式声明的复制构造函数,该构造函数不复制任何内容。

当您声明复制构造函数时,您将负责完全基于所复制对象的内容来构造新对象。

你的构造函数什么都不做。你最终构建了一个空对象。

dishes.push_back(ingredientsA);

所以,你创建了一个列表。然后通过push_back()ingredientsA复制到列表的末尾。

由于您的复制构造函数并没有真正复制任何内容,因此您最终会将一个完全空的类实例复制到dishes列表中。

只需去掉显式复制构造函数。它没有明显的目的。

//add to our list of entries
list< ListA > dishes;
dishes.push_back(ingredientsA);
dishes.push_back(ingredientsB);

使用复制构造函数将List放入std::List中,并且您的复制构造函数覆盖默认构造函数,并且不执行