Printing out a list that is private member in class

Mar 2, 2018 at 2:08pm
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?
Mar 2, 2018 at 2:33pm
What does the public interface of Lexicon have?
Mar 2, 2018 at 2:40pm
create a public "getter" method inside Lexicon, which could, for example, return a const reference to the private myLexicon object.
Mar 2, 2018 at 3:34pm
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 Mar 2, 2018 at 3:50pm
Topic archived. No new replies allowed.