0

I have created a list of objects of a class.

The class has an overloaded ostream << operator to output customer data in a structured way.

What I am trying to do is loop over the list of objects and call cout on the object in the iteration.

Code for the loop is as follows:

for (list<Kunde>::iterator it = this->kun_list.begin(); it != this->kun_list.end(); ++it) {
                cout << it << endl;
            }

With Kunde being the class with the overloaded << operator and kun_list being the list of objects of type Kunde.

friendly overload within the Kunde class:

friend ostream& operator<< (ostream& os, Kunde& kd) {
    os << "__Kundendaten__" << endl;
    os << "Name: " << kd.vorname << " " << kd.name << endl;
    os << "Geburtsjahr: "<< kd.geburtsjahr << endl;
    os << "Adresse: " << kd.strasse << " " << kd.hausnummer << endl << kd.plz << " " << kd.ort << endl;
    os << "Telefon: " << kd.telefonnummer << endl;
    string fschein = "Nein.";
    if (kd.klasse_a_vorhanden) {fschein = "Ja.";}
    os << "Führerschein Kl. A vorhanden: " << fschein << endl;
    return os;
};

The above loop does not work because I am using the list iterator instead of an object of class Kunde. I can access members of Kunde via it→member but how do I use that iterator as reference to the whole object?

Thanks!

Franz
  • 235
  • 3
  • 14
  • 1
    The equivalent of `->` without referencing a member is unary `*`. It works for iterators just like for pointers. (But the answer already has a suggestion that is better than your loop construct anyway.) – user17732522 Jun 02 '22 at 19:32

1 Answers1

3

Use a const reference loop over the container:

for (const auto & kunde : kun_list) {
            cout << kunde << endl;
}

Obviously you also have to fix <<:

friend ostream& operator<< (ostream& os, const Kunde& kd) {...}
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42
  • 1
    `const` will not work since OP used a non-`const` reference in the `operator<<`. (Of course the latter should be fixed.) – user17732522 Jun 02 '22 at 19:33
  • That's it, thanks to both of you! I will have to wait a few minutes until I can mark as solved. – Franz Jun 02 '22 at 19:36
  • worth to notice that ```auto``` can [prevent implicit conversions](https://stackoverflow.com/questions/32510183/can-the-use-of-c11s-auto-improve-performance) – francesco Jun 02 '22 at 19:49