<< operator for a nested class

I am trying to overload the <statement for a nested ArticleIterator class.

 // ... class ArticleContainer { public: class ArticleIterator { // ... friend ostream& operator<<(ostream& out, const ArticleIterator& artit); }; // ... }; 

If I define the <<operator as usual, I get a compiler error.

 friend ostream& operator<<(ostream& out, const ArticleContainer::ArticleIterator& artit) { 

Error 'friend' used outside of class . How to fix it?

+4
source share
3 answers

You do not put the friend keyword when defining a function, only when declaring it.

 struct A { struct B { friend std::ostream& operator<<(std::ostream& os, const B& b); }; }; std::ostream& operator<<(std::ostream& os, const A::B& b) { return os << "b"; } 
+8
source

You must declare it as a friend inside the class, and then define it outside the class without the keyword friend.

 class ArticleContainer { public: class ArticleIterator { // ... friend ostream& operator<<(ostream& out, const ArticleIterator& artit); }; }; // No 'friend' keyword ostream& operator<<(ostream& out, const ArticleIterator& artit); 
+2
source

The friend keyword is used in the declaration to indicate that this func / class is a friend. In a definition outside the class, you cannot use this keyword. Just delete it

+1
source

All Articles