In the book I am reading he gives an example, for a linked list with diffrent data types.
Code:class list;
class block
{
block *pnext;
public:
block(void)
{
pnext = NULL;
}
virtual void show(void)=0;
friend class list;
};
class numbers: public block
{
int num;
public:
numbers(int Inum)
{
num = Inum;
}
void show(void)
{
cout << "num = " << num << "\n";
}
};
class strings : public block
{
char str[256];
public:
strings(char *Istr)
{
strcpy(str, Istr);
}
void show(void)
{
cout << "str = " << str << "\n";
}
};
class list
{
block *phead;
public:
list(void)
{
phead = NULL;
}
void add(block *pnewb)
{
if ( ! phead )
phead = pnewb;
else
{
pnewb->pnext = phead;
phead = pnewb;
}
}
void show(void)
{
block *ptmp ;
for ( ptmp = phead; ptmp ; ptmp = ptmp->pnext)
ptmp->show();
}
};
int main(int argc, char *argv[])
{
char strtbl[3][80] = { "one", "two", "three" };
numbers *pn;
strings *ps;
int i;
list l1;
for ( i = 0 ; i < 3 ; ++i )
{
pn = new numbers(i+1);
ps = new strings(strtbl[i]);
l1.add(pn);
l1.add(ps);
}
l1.show();
system("PAUSE");
return EXIT_SUCCESS;
}
The output:
str = three
num = 3
str = two
num = 2
str = one
num = 1
Press any key to continue . . .
End the output:
1 ) Is there some way to know wheter a block pointer, points to numbers or to strings ?
2 ) As a home work. I need to do :
a) function that removes a cell from the linked list. ( How do I find it ? suppose the user wants to remove the cell strings "two")
b) function that finds a cell.
I tought :
1) adding to the class block the type of the data
2) overloading the operator == in block as a pure function.
Any help
Thank you.