为什么好友函数无法访问C ++中的嵌套类定义?

时间:2019-07-04 08:50:29

标签: c++ templates operator-overloading

我正在使用cpp中的模板编写Queue类,并且我想重载“ <<”运算符。我在Queue类中有一个嵌套类的定义,需要在operator <<定义中实例化它,因此我将它称为朋友。我不明白为什么编译器不允许我将嵌套函数声明为朋友,却无法创建任何嵌套类的对象。这是代码:

 template <class T>
 class Queue
 {

 private:

 class Cell {
    ....
 }

 };

重载的运算符:

声明:

template <class T>
friend std::ostream& operator<<(std::ostream& os, const Queue<T>&);

定义:

    template <class T>
    std::ostream& operator<<(std::ostream& os, const Queue<T>& queue) {

    Cell* finder = queue.firstElement;
    for (int i = 1; i < queue.size + 1; i++) {

    os << i << ". " << finder->getElem() << std::endl;
    finder = finder->getNext();

    }

    return os;

    }

我已经使用“ auto”关键字解决了问题,但是我想知道为什么以前的解决方案不能正常工作。谢谢你的帮助。 使用自动关键字的解决方案:

    template <class T>
    std::ostream& operator<<(std::ostream& os, const Queue<T>& queue) {

    auto* finder = queue.firstElement;
    for (int i = 1; i < queue.size + 1; i++) {

    os << i << ". " << finder->getElem() << std::endl;
    finder = finder->getNext();

    }

    return os;

    }

0 个答案:

没有答案