Printing out a list that is private member in class

Hey! How can I print out a list using overloaded operator<< when my list is a private member of my Lexicon class?

1
2
3
4
5
 class Lexicon
{
    private:
        list<string> myLexicon;
        int numElements;


1
2
3
4
5
6
7
8
9

ostream& operator<<(ostream &os, const Lexicon& obj){
    list<string>::iterator it;    	
    for(it = obj.myLexicon.begin(); it != obj.myLexicon.end(); it++){
	os << (*it) << endl;	
    }
	return os;
}



everytime I compile it it gives me the error that my = is not overloaded or that .begin is not a function of my class. How would I be able to access the list to print it out?
What does the public interface of Lexicon have?
create a public "getter" method inside Lexicon, which could, for example, return a const reference to the private myLexicon object.
you can make that overload friend of the class and move your code inside the class. This way you don't need to expose your private data to everyone trough a getter


1
2
3
4
5
6
7
8
9
10
11
12
13
class Lexicon
{
	list<string> myLexicon;
	int numElements;

	friend ostream& operator<<(ostream &os, const Lexicon& obj) {
		list<string>::iterator it;
		for (it = obj.myLexicon.begin(); it != obj.myLexicon.end(); it++) {
			os << (*it) << endl;
		}
		return os;
	}
};


or friend declaration inside, definition outside

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Lexicon
{
	list<string> myLexicon;
	int numElements;

	friend ostream& operator<<(ostream &os, const Lexicon& obj);
};

ostream& operator<<(ostream &os, const Lexicon& obj) {
		list<string>::iterator it;
		for (it = obj.myLexicon.begin(); it != obj.myLexicon.end(); it++) {
			os << (*it) << endl;
		}
		return os;
	}
Last edited on
Topic archived. No new replies allowed.