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!
CodePudding user response:
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) {...}