First I want to make it clear that this is a homework based question. That being the case, I want to ‘understand’ where my thinking is going haywire and not just have an answer given 😉
I have a class called RegistrationList that is derived from QList like such:
class RegistrationList : public QList<Registration *>
The Registration object has two children classes so the list RegistrationList have pointers to objects of the original Registration class as well as its two children:
class GuestRegistration : public Registration
and
class StudentRegistration : public Registration
the class RegistrationList must have a function prototyped like this:
void displayList();
What this function needs to do is call a function called
QString toString();
in all the objects in the list.
Now this is what I have for the implementation of the
void displayList();
member function of RegistrationList class:
void RegistrationList::displayList()
{
QTextStream cout(stdout);
cout << "\nHere follows a list of all registrations:";
cout << "\n=========================================\n";
foreach(Registration *r, this) { r->toString(); }
}
But the compiler doesn’t like it at all. The way I see this is that I want to iterate over a list containing a collection of Registration like objects. Each of these objects have a member function called
toString();
to print out pretty formatted info. This works 100%. If I comment out the foreach line the code compiles with no issues. The only thing I can think of is that foreach doesn’t like to have
this
as its second parameter.
It is not a must that I have to use foreach but it will bug me to no end if I cannot find out why it doesn’t work although it ‘seems’ as if it should…
foreach requires the second argument to be a reference to an object. You therefore need to dereference this:
You also probably want to write r->toString(); to the stream you have just created.