views:

64

answers:

3

I'm trying to overload the << operator for the nested class ArticleIterator.

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

If I define operator<< like I usually do, I get a compiler error.

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

The error is 'friend' used outside of class. How do I fix this?

+3  A: 

You don't put the friend keyword when defining the 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";
}
Peter Alexander
come to think of it, this isn't that much about declarations and definitions. You can define the friend lexically inside the class and you can redeclare the function outside the class without the friend keyword. I think this is about where the particular declaration appears - friend specifier can apply only to function declarations lexically inside the class definition
Armen Tsirunyan
+1  A: 

the friend keyword is used in the declaration to specify that this func/class is a friend. In the definition outside the class you may not use that keyword. Just remove it

Armen Tsirunyan
+2  A: 

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

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

// No 'friend' keyword
ostream& operator<<(ostream& out, const ArticleIterator& artit);
xPheRe