code to display linked list:

for (Node *cur = head; cur != NULL; cur = cur->next)
  cout << cur->item << endl;

in the header file:

struct Node
{ int item;
Node *next;

It will declare a new pointer called cur, set it equal to head, and keep going until cur = null (the end of the linked list). And each time it sets cur to the next item then prints it.

8 Years
Discussion Span
Last Post by hjong.mahjong

forgot my question

prewritten header file:

#ifndef PHONE_H
#define PHONE_H

#include <iostream>
#include <string>
using namespace std;

struct PhoneBookItem  {
	string lastname;
	string firstname;
	string phone;
	PhoneBookItem* next;
	PhoneBookItem(const string& l, const string& f, const string& ph);

class PhoneBook  {
	PhoneBook(const PhoneBook&);

	PhoneBook& operator=(const PhoneBook&);

	bool IsEmpty() const;
	int Size() const;
	bool Insert(const string& last, const string& first, const string& ph);
	bool Delete(const string& last, const string& first);
	bool Lookup(const string& last, const string& first, string& ph) const;

	friend ostream& operator<< (ostream&, const PhoneBook&);

	void Clear();
	void Copy(const PhoneBook&);

	PhoneBookItem* head;   // points to head of the phone book
	int num;     // the number of entries in the phone book


the implementation of the output function in the cpp file:

ostream& operator << ( ostream &out, const PhoneBook &pb)
       for (PhoneBookItem *cur = head; cur != NULL; cur = cur->next)
        out << "a phonebook item" << endl;

   return out;

why does it give me this compiler error about the for loop:
`head' undeclared (first use this function)

thanks in advance.


You haven't told the compiler that "head" has anything to do with the PhoneBook class, so it doesn't know to look there. Perhaps you meant pb.head instead of head? Since pb is of type PhoneBook, the compiler knows to look for a data member of the PhoneBook class called "head". Without the "pb" in front, it doesn't know that is what you are referring to.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.