/* Name: Game Lobby Copyright: tonyee Author: tonyee Date: 15-03-09 20:44 Description: code for study */ #include <iostream> #include <string> using namespace std; class Player { public: Player(const string& name = "") :m_Name(name),m_pNext(0){} string GetName() const { return m_Name; } Player* GetNext() const { return m_pNext; } void SetNext (Player* next) { m_pNext = next; } private: string m_Name; Player* m_pNext; // 指向列表中下一个玩家的指针 }; class Lobby { friend ostream& operator<<(ostream& os, const Lobby& aLobby); public: Lobby(): m_pHead(0) {}; ~ Lobby() { Clear(); }; void AddPlayer(); void RemovePlayer(); void Clear(); private: Player* m_pHead; }; void Lobby::AddPlayer() { // 创建一个新的玩家节点 cout << "Please enter a name of the new player: "; string name; cin >> name; Player* pNextPlayer = new Player(name); // 如果列表是空的,则将这个新玩家放在列表的开始处 if (m_pHead == 0) { m_pHead = pNextPlayer; } else { Player* pIter = m_pHead; while(pIter->GetNext() != 0) { pIter = pIter->GetNext(); } pIter->SetNext(pNextPlayer); } } void Lobby::RemovePlayer() { if (m_pHead == 0) { cout << "The game labby is empty.No one to romove!/n"; } else { Player* pTemp = m_pHead; m_pHead = m_pHead->GetNext(); delete pTemp; } } void Lobby::Clear() { while (m_pHead != 0) { RemovePlayer(); } } ostream& operator<<(ostream& os, const Lobby& aLobby) { Player* pIter = aLobby.m_pHead; os << "/nHead's who's in the game lobby:/n"; if (pIter == 0) { os << "The lobby is empty./n"; } else { while (pIter != 0) { os << pIter->GetName() << endl; pIter = pIter->GetNext(); } } return os; } int main(int argc, char *argv[]) { Lobby myLobby; int choice; do { cout << myLobby; cout << "/nGAME LOBBY/n"; cout << "0 - Exit the program./n"; cout << "1 - Add a player to the lobby./n"; cout << "2 - Remove a player from the lobby./n"; cout << "3 - Clear the lobby./n"; cout << endl << "Enter choice: "; cin >> choice; switch (choice) { case 0: cout << "Good-bye./n"; break; case 1: myLobby.AddPlayer(); break; case 2: myLobby.RemovePlayer(); break; case 3: myLobby.Clear(); break; default: cout << "That was not a valid choice./n"; } } while( choice != 0); system("PAUSE"); return 0; }