运营商LT;<对于嵌套类

时间:2010-10-25 14:13:36

标签: c++ operator-overloading friend

我正在尝试重载<<嵌套类ArticleIterator的运算符。

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

如果我定义运算符&lt;&lt;就像我通常做的那样,我得到了一个编译器错误。

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

错误为'friend' used outside of class。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:8)

在定义函数时,只有在声明函数时才放置friend关键字。

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";
}

答案 1 :(得分:2)

您必须在课堂内将其声明为朋友,然后在没有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 :(得分:1)

在声明中使用friend关键字来指定此func / class是朋友。在类外的定义中,您可能不会使用该关键字。只需删除它

相关问题