jyaan
December 26th, 2008, 06:06 PM
What's going on with this code? It's taken directly out of a textbook by Robert Lafore : OOP in C++. GCC claims "ISO C++ forbids declaration of ‘link’ with no type", yet link is defined directly above with a struct... No other errors are given, aside from later references to pointers of type link. The typedef keyword does not make any difference.
// linklist.cpp
// linked list
#include <iostream>
using namespace std;
struct link // one element of list
{
int data; // data item
link *next; // pointer to next link
};
class linklist // a list of links
{
private:
link *first; // pointer to first link
public:
linklist()
{ first = NULL; } // no first link
void additem(int d); // add data item (one link)
void display(); // display all links
};
void linklist::additem(int d)
{
link *newlink = new link; // make a new link
newlink->data = d; // give it data
newlink->next = first; // it points to next link
first = newlink; // now first points to this
}
void linklist::display()
{
link *current = first; // set ptr to first link
while (current != NULL) // quit on last link
{
cout << current->data << endl; // print data
current = current->next; // move to next link
}
}
int main()
{
linklist li;
li.additem(25);
li.additem(36);
li.additem(49);
li.additem(64);
li.display();
return 0;
}
// linklist.cpp
// linked list
#include <iostream>
using namespace std;
struct link // one element of list
{
int data; // data item
link *next; // pointer to next link
};
class linklist // a list of links
{
private:
link *first; // pointer to first link
public:
linklist()
{ first = NULL; } // no first link
void additem(int d); // add data item (one link)
void display(); // display all links
};
void linklist::additem(int d)
{
link *newlink = new link; // make a new link
newlink->data = d; // give it data
newlink->next = first; // it points to next link
first = newlink; // now first points to this
}
void linklist::display()
{
link *current = first; // set ptr to first link
while (current != NULL) // quit on last link
{
cout << current->data << endl; // print data
current = current->next; // move to next link
}
}
int main()
{
linklist li;
li.additem(25);
li.additem(36);
li.additem(49);
li.additem(64);
li.display();
return 0;
}