【问题标题】:Why does my own output stream class not work? [duplicate]为什么我自己的输出流类不起作用? [复制]
【发布时间】:2013-01-21 01:00:38
【问题描述】:

可能重复:
std::endl is of unknown type when overloading operator<<

#include <iostream>

using namespace std;

struct OutputStream
{
    template<class T>
    OutputStream& operator <<(const T& obj)
    {
        cout << obj;

        return *this;
    }
};

OutputStream os;

int main()
{    
    os << 3.14159 << endl; // Compilation Failure!
}

VC++ 2012 编译器报错:

错误 C2676:二进制 '

【问题讨论】:

  • 你没有定义 endl
  • T不适用于endl吗?
  • 我认为它会适用,但代码确实在没有 endl 的情况下编译。我就等大佬回答了。 :p
  • 好吧,因为它是完全重复的......删除这个?
  • 我已投票关闭我的这篇文章。

标签: c++ class stream iostream template-function


【解决方案1】:

原因是编译器无法推断出T的类型,因为std::endl是定义为的函数模板

template <class charT, class traits>
  basic_ostream<charT,traits>& endl ( basic_ostream<charT,traits>& os );

在 IOStreams 中克服它的方法是提供适当的 operator&lt;&lt; 重载:

OutputStream& operator <<(std::ostream& ( *pf )(std::ostream&))
{
  cout << pf;
  return *this;
}

【讨论】:

  • 好答案!简洁通用!
猜你喜欢
  • 1970-01-01
  • 2019-09-07
  • 2015-05-03
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多