c++ - operator<< 重载调用打印函数麻烦

标签 c++ operator-overloading ostream

好吧,我在尝试为我的模板类重载 << 运算符时遇到了一些困难。要求是 << 运算符必须调用为此类定义的 void print 函数。

这是模板标题中的重要内容:

template <class T>
class MyTemp {
public:
    MyTemp();           //constructor

    friend std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a);

    void print(std::ostream& os, char ofc = ' ') const;

这是我的打印函数,基本上它是一个 vector ,将最后一个元素打印到第一个:

    template <class T>
void Stack<T>::print(std::ostream& os, char ofc = ' ') const
{
    for ( int i = (fixstack.size()-1); i >= 0 ; --i)
    {
        os << fixstack[i] << ofc;
    }
}

下面是我如何重载运算符<<:

    template <class T>
std::ostream& operator<< (std::ostream& os, const Stack<T>& a)
{
    // So here I need to call the a.print() function
}

但我收到“未解析的外部符号”错误。所以我真的想我有两个问题。首先,是修复上述错误的方法。其次,一旦它被修复,我会在 << 重载中调用 a.print(os) 吗?我知道它需要返回一个 ostream。任何帮助将不胜感激!

最佳答案

最简单的做法就是离开 print公开(如您的示例中所示),因此运算符(operator)不需要成为 friend 。

template <class T>
class MyTemp {
public:
    void print(std::ostream& os, char ofc = ' ') const;
};

template <class T>
std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a) {
    a.print(os);
    return os;
}

如果你确实需要它是私有(private)的,那么你需要声明正确的模板特化成为 friend - 你的 friend声明在周围的命名空间中声明一个非模板运算符,而不是模板。不幸的是,要使模板成为 friend ,您需要事先声明它:

// Declare the templates first
template <class T> class MyTemp;
template <class T> std::ostream& operator<< (std::ostream&, const MyTemp<T>&);

template <class T>
class MyTemp {
public:
    friend std::ostream& operator<< <>(std::ostream& os, const MyTemp<T>& a);
    // With a template thingy here  ^^

private:
    void print(std::ostream& os, char ofc = ' ') const;
};

template <class T>
std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a) {
    a.print(os);
    return os;
}

或者您可以定义内联运算符:

template <class T>
class MyTemp {
public:
    friend std::ostream& operator<<(std::ostream& os, const MyTemp<T>& a) {
        a.print(os);
        return os;
    }

private:
    void print(std::ostream& os, char ofc = ' ') const;
};

最后一个问题:

Second, once that is fixed would I just call a.print(os) inside << overload? I know it needs to return an ostream though.

它确实需要返回一个 ostream - 所以只返回传入的那个,就像我的示例代码一样。

关于c++ - operator<< 重载调用打印函数麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9408688/

相关文章:

c++ - qsort比较编译错误

C++ 链表 : Overload bracket operators []

c++ - QTcpServer 应用程序中 Qt C++ 中的槽和信号

c++ - 为什么标准容器迭代器不重载 `->*` ?

c++ - 使用 C++ union ,当你想要的成员未知时

c++ - ostream 问题

c++ - ostream 和 << 重载的问题

c++ - 在 C++ 中继承和覆盖 ostream 运算符

c++ - 调整大小后保持对 vector 元素的引用有效

c++ - 为什么这段代码在调试时慢了 100 倍?