【问题标题】:operator<< for nested class运算符<< 用于嵌套类
【发布时间】:2011-04-30 05:55:53
【问题描述】:

我正在尝试为嵌套类 ArticleIterator 重载

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

如果我像往常一样定义运算符

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

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

【问题讨论】:

    标签: c++ operator-overloading friend


    【解决方案1】:

    你不要在定义函数的时候加上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";
    }
    

    【讨论】:

    • 想一想,这与声明和定义无关。您可以在类内部按词法定义朋友,并且可以在没有朋友关键字的情况下在类外部重新声明函数。我认为这是关于特定声明出现的位置 - 朋友说明符只能应用于类定义中的词法函数声明
    【解决方案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);
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2012-02-03
        • 1970-01-01
        • 2020-03-10
        • 2013-09-20
        • 1970-01-01
        • 2011-10-29
        • 1970-01-01
        相关资源
        最近更新 更多