#include<iostream>
#include<string>
using namespace std;
class car
{
public:
car(const string& name = " "); //cars name
string getName() const; //returns name
car* getNext() const;
void setNext(car* next);
private:
string m_name; //naame of car
car* m_pNext; //pointer to next car on the list
};
car::car(const string& name):
m_name(name),
m_pNext(0)
{}
string car::getName() const
{
return m_name;
}
car* car::getNext() const
{
return m_pNext;
}
void car::setNext(car* next)
{
m_pNext = next;
}
class Garage
{
friend ostream& operator<<(ostream& os, const Garage& aGarage);
public:
Garage();
~Garage();
void AddCar();
void DeleteCar();
void Clear();
private:
car* m_pHead;
};
Garage::Garage():
m_pHead(0)
{}
Garage::~Garage()
{
Clear();
}
void Garage::AddCar()
{
//getting new car
cout << "Please enter new name of car: " << endl;
string name;
cin >> name;
car* pNewCar = new car(name);
//if list is empty make new new head
if( m_pHead == 0)
{
m_pHead = pNewCar;
}
//otherwise end of the list
else
{
car* pIter = m_pHead;
while(pIter->getNext() != 0)
{
pIter = pIter->getNext();
}
pIter->setNext(pNewCar);
}
}
void Garage::DeleteCar()
{
if(m_pHead == 0)
{
cout << "The garage is empty !" << endl;
}
else
{
car* pTemp = m_pHead;
m_pHead = m_pHead->getNext();
delete pTemp;
}
}
void Garage::Clear()
{
while(m_pHead != 0)
{
DeleteCar();
}
}
ostream& operator<<(ostream& os, const Garage& aGarage)
{
car* pIter = aGarage.m_pHead;
os << "\nHere's what cars are in the garage:\n";
if(pIter == 0)
{
os << "The garage is empty.\n";
}
else
{
while(pIter != 0)
{
os << pIter->getName() << endl;
pIter = pIter->getNext();
}
}
return os;
}
int main()
{
Garage myGarage;
int choice;
do
{
cout << myGarage;
cout << "Here you'll have your own car garage.\n";
cout << "0 - Quit" << endl;
cout << "1 - Add Car" << endl;
cout << "2 - Delete Car" << endl;
cout << "3 - Clear Car" << endl;
cin >> choice;
switch(choice)
{
case 0:cout << "Thanks for Playing" << endl; break;
case 1:myGarage.AddCar(); break;
case 2:myGarage.DeleteCar(); break;
case 3:myGarage.Clear(); break;
default: cout << "Invalid choice.." << endl;
}
}while(choice != 0);
return 0;
}
This is a some code I got from reading the Beginning C++ through Game Programming, it explains it in the book, but I really don't understand. I was wondering if anyone could help explain. I get really confused around the Garage Add member fucntion, that's what confuses most.