Я пытался создать шаблонный класс (называемый List), в котором хранятся объекты различного типа. Я создал базовый класс, чтобы он был похож на базовый в моей программе и на класс человека. База может создавать новых людей и иметь к ним доступ, имеет (приватный) указатель на List * first_h (в каждом списке хранится Human * me, List * next и List * first_h (first_h в списке)).
Проблема в том, что когда я добавляю на базу более 1 человека, я не могу отображать их должным образом. Я думаю, что это из-за создания нового метода Human in Base (void Base :: create_human (string name)), но все, что я сделал, не сработало.
Есть мои занятия:
class Human
{
private:
string name;
public:
Human(string name) { this->name = name; }
void display() { cout << "My name: " << name << endl; }
};
template <class T>
class List
{
private:
T* me;
List <T>* next;
List <T>* first;
public:
void set_me(T* me) { this->me = me; }
T* get_me() { return this->me; }
void set_next(List* next) { this->next = next; }
List <T>* get_next() { return this->next; }
void set_first(List* first) { this->first = first; }
List <T>* get_first() { return this->first; }
void add(T*& created);
void display();
};
class Base
{
private:
List <Human>* first_h;
public:
void set_first_h(List <Human>*& first) { this->first_h = first; }
List <Human>* get_first_h() { return this->first_h; }
void create_human(string name)
{
Human* created = new Human(name);
this->first_h->add(created);
}
};
и методы:
template <class T>
void List<T>::add(T*& created)
{
List <T>* temp = this->get_first();
List <T>* new_list;
if ((this->get_me()) == nullptr)
{
this->set_next(nullptr);
this->set_me(created);
this->set_first(this);
}
else
{
new_list = new List <T>;
temp = this->get_first();
while (temp != nullptr)
{
temp = temp->get_next();
}
new_list->set_next(nullptr);
new_list->set_first(this->get_first());
temp->set_next(new_list);
}
}
template <class T>
void List<T>::display()
{
List <T>* temp_list = this;
T* temp;
if (temp_list == nullptr)
{
std::cout << "There is nothing!" << endl;
}
while (temp_list != nullptr)
{
temp = temp_list->get_me();
temp->display();
temp_list = temp_list->get_next();
}
std::cout << "End!" << endl;
}
и моя основная функция:
int main()
{
Base Main;
List <Human>* first_h = new List <Human>();
Main.set_first_h(first_h);
Main.create_human("Jane");
Main.create_human("John");
Main.create_human("Mary");
Main.get_first_h()->display();
system("pause");
return 0;
}
Извините за мой английский и заранее спасибо!
Edit:
Я узнал, что было не так:
в функции добавления:
new_list->set_next(nullptr);
new_list->set_me(created);
new_list->set_first(this->get_first());
temp->set_next(new_list);
Я забыл о:
new_list->set_me(created);
- ошибка в функции add, как написал один из вас.