【问题标题】:overloading operator ostream for template class in c++ not workingc++中模板类的重载运算符ostream不起作用
【发布时间】:2021-02-12 19:31:32
【问题描述】:

所以我有这个模板类:

template<class T = int, unsigned int SIZE =2>
class FixedPoint {
   public:
            explicit FixedPoint(T dollars = 0);
            FixedPoint(T dollars, T cents);

            friend std::ostream& operator<<(std::ostream& os ,const FixedPoint& price);

    private:
        static long digitsAfterDotFactor();
        long sizeAfterDot;
        T dollars;
        T cents;
};

这是它在 h 文件中的类下的定义

template<class T,unsigned int SIZE>
inline std::ostream& operator<<(std::ostream& os ,const FixedPoint<T,SIZE>& price){
    os << price.dollars << "." << price.cents;
    return os;
}

代码给了我以下错误:

friend declaration ‘std::ostream& operator<<(std::ostream&, const FixedPoint<T, SIZE>&)’ declares a non-template function

我尝试在声明中添加模板名称,但它无法识别 T 类,我该怎么办?我应该为每种类型制作规范模板吗?

【问题讨论】:

  • 如果你想要类定义之外的函数定义,将friend声明更改为friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os ,const FixedPoint&lt;T, SIZE&gt; &amp; price)(即提供模板参数)。我假设 &lt;iostream&gt;(或者,更好的是 &lt;iosfwd&gt;)之前已包含在内。
  • 附注:os &lt;&lt; price.dollars &lt;&lt; "." &lt;&lt; price.cents; 会将 1 美元和 5 美分打印为 1.5 而不是 1.05
  • 是的,谢谢,我知道,我只是一次解决一个问题,哈哈,编译时错误需要更多注意。

标签: c++ templates operator-overloading friend ostream


【解决方案1】:

正如错误消息所说,friend 声明声明了一个非模板operator&lt;&lt;,但它被定义为模板,它们不匹配。

您可以参考运算符模板进行friend 声明,例如

// forward declaration
template<class T = int, unsigned int SIZE =2>
class FixedPoint;

// declaration
template<class T,unsigned int SIZE>
std::ostream& operator<<(std::ostream& os ,const FixedPoint<T,SIZE>& price);

template<class T, unsigned int SIZE>
class FixedPoint {
   public:
            ...
            friend std::ostream& operator<< <T, SIZE> (std::ostream& os ,const FixedPoint<T, SIZE>& price);
            // or just
            // friend std::ostream& operator<< <> (std::ostream& os ,const FixedPoint& price);
            ...
};

// definition
template<class T,unsigned int SIZE>
inline std::ostream& operator<<(std::ostream& os ,const FixedPoint<T,SIZE>& price){
    os << price.dollars << "." << price.cents;
    return os;
}

【讨论】:

  • 谢谢它的工作,但你能解释一下为什么会发生这种情况
  • @AladinHandoklo 您只需要匹配friend 声明和operator&lt;&lt; 的定义。非模板与模板不起作用,它们指的不是同一个东西。
【解决方案2】:

您可以在类模板本身中定义friend 成员函数,

template<class T = int, unsigned int SIZE =2>
class FixedPoint {
  public:
      /* ... */

      friend std::ostream& operator<<(std::ostream& os ,const FixedPoint& price)
      {
          return os << price.dollars << "." << price.cents;
      }

      /* ... */
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多