Hello ladies and gents,
I'm trying to include a copy constructor and an assignement operator into this code wich has two separate classes, the idea is to copy the last name that was entered. Problem is, I can't seem to grasp how to get acces to the copy constructor in main nor am I sure that the copy constructor is written correctly?
Could someone help me out with this program:
//Lobby
//Simulate a lobby where people wait
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(const string& name = ""):m_Name(name), m_pNext(NULL){}
Person(const Person& copyName);
string GetName() const { return m_Name;}
Person* GetNext() const { return m_pNext;}
void SetNext(Person* next) { m_pNext = next;}
private:
string m_Name;
Person* m_pNext; // pointer to next name in list
};
Person::Person(const Person& copyName)
{
cout << "Copy constructor called...\n";
m_pNext = new Person;
*m_pNext = copyName.GetName();
}
class Lobby
{
friend ostream& operator<<(ostream& os, const Lobby& aLobby);
public:
Lobby():m_pHead(NULL){}
~Lobby() { Clear();}
void AddName();
void RemoveName();
void Clear();
private:
Person* m_pHead;
};
void Lobby::AddName()
{
//create a new name node
cout << "Please enter the name of the new person: ";
string name;
cin >> name;
Person* pNewName = new Person(name);
//if list is empty, make head of list this new name
if (m_pHead == NULL)
{
m_pHead = pNewName;
}
//otherwise find the end of the list and add the name there
else
{
Person* pIter = m_pHead;
while (pIter->GetNext() != NULL)
{
pIter = pIter->GetNext();
}
pIter->SetNext(pNewName);
}
}
void Lobby::RemoveName()
{
if (m_pHead == NULL)
{
cout << "The lobby is empty. No one to remove.\n";
}
else
{
Person* pTemp = m_pHead;
m_pHead = m_pHead->GetNext();
delete pTemp;
}
}
void Lobby::Clear()
{
while (m_pHead != NULL)
{
RemoveName();
}
}
ostream& operator<<(ostream& os, const Lobby& aLobby)
{
Person* pIter = aLobby.m_pHead;
os << "\nHere's who's in the lobby:\n";
if (pIter == NULL)
{
os << "The lobby is empty.\n";
}
else
{
while (pIter != NULL)
{
os << pIter->GetName() << endl;
pIter = pIter->GetNext();
}
}
return os;
}
int main()
{
Lobby myLobby;
int choice;
do
{
cout << myLobby;
cout << "\nLOBBY\n";
cout << "0 - Exit the program.\n";
cout << "1 - Add a person to the lobby.\n";
cout << "2 - Remove a person from the lobby.\n";
cout << "3 - Clear the lobby.\n";
cout << "4 - Copy the last name.\n";
cout << endl << "Enter choice: ";
cin >> choice;
switch(choice)
{
case 0:
cout << "Good-bye.\n";
break;
case 1:
myLobby.AddName();
break;
case 2:
myLobby.RemoveName();
break;
case 3:
myLobby.Clear();
break;
//case 4:
//Person. //<-- how to write the link to getting
//break; //the copy???
default:
cout << "That was not a valid choice.\n";
}
} while (choice != 0);
cout << "Press enter to exit!\n";
cin.ignore(1, '\0');
return 0;
}
Thank you.