C++ 对象创建和列表
C++ Object Creation & Lists
Main 方法 -> 包含一系列 Family 对象。 Family -> 包含 Person 对象列表。
创建 Family 对象后,如何强制它为 Family 的每个新实例创建一个新的“Person”对象列表?
目前主列表中的所有Family对象共享一个Person链表..
非常感谢您的想法。我必须使用链表的链表...
#include <iostream>
#include <list>
using namespace std;
class Family
{
private:
int family_id;
public:
int getFamilyId();
void createPerson(int id, string name);
void readPersonName();
Family(int id);
~Family();
};
list <Person> people;
Family::Family(int id)
{
family_id = id;
}
Family::~Family(void){};
int Family::getFamilyId()
{
return family_id;
};
void Family::createPerson(int id, string name)
{
people.push_back(Person(id, name));
};
void Family::readPersonName()
{
list<Person>::iterator itr;
for(itr = people.begin(); itr != people.end(); itr++)
cout << itr->get_person_name() << '\n';
};
"Upon creation of a Family object, how do I force it to create a new list of ‘Person’ objects for every new instance of Family??"
你为什么不直接将该列表声明为 class 成员?
class Family {
private:
int family_id;
public:
int getFamilyId();
void createPerson(int id, string name);
void readPersonName();
Family(int id);
~Family();
private:
list <Person> people; // <<<<<
};
"I have to use a linked list of linked lists..."
我不完全理解你问题的这一部分。您是否也需要为所有人保留一个全局列表?
在这种情况下,您应该使用以下人员的共享对象列表:
class Family {
// ....
void createPerson(int id, string name) {
people.push_back(new Person(id,name));
allPeople.push_back(people.back());
}
private:
list <shared_ptr<Person>> people;
};
list<shared_ptr<Person>> allPeaople;
Main 方法 -> 包含一系列 Family 对象。 Family -> 包含 Person 对象列表。
创建 Family 对象后,如何强制它为 Family 的每个新实例创建一个新的“Person”对象列表?
目前主列表中的所有Family对象共享一个Person链表..
非常感谢您的想法。我必须使用链表的链表...
#include <iostream>
#include <list>
using namespace std;
class Family
{
private:
int family_id;
public:
int getFamilyId();
void createPerson(int id, string name);
void readPersonName();
Family(int id);
~Family();
};
list <Person> people;
Family::Family(int id)
{
family_id = id;
}
Family::~Family(void){};
int Family::getFamilyId()
{
return family_id;
};
void Family::createPerson(int id, string name)
{
people.push_back(Person(id, name));
};
void Family::readPersonName()
{
list<Person>::iterator itr;
for(itr = people.begin(); itr != people.end(); itr++)
cout << itr->get_person_name() << '\n';
};
"Upon creation of a Family object, how do I force it to create a new list of ‘Person’ objects for every new instance of Family??"
你为什么不直接将该列表声明为 class 成员?
class Family {
private:
int family_id;
public:
int getFamilyId();
void createPerson(int id, string name);
void readPersonName();
Family(int id);
~Family();
private:
list <Person> people; // <<<<<
};
"I have to use a linked list of linked lists..."
我不完全理解你问题的这一部分。您是否也需要为所有人保留一个全局列表?
在这种情况下,您应该使用以下人员的共享对象列表:
class Family {
// ....
void createPerson(int id, string name) {
people.push_back(new Person(id,name));
allPeople.push_back(people.back());
}
private:
list <shared_ptr<Person>> people;
};
list<shared_ptr<Person>> allPeaople;