【问题标题】:ostream operator<< call parent ostreamostream 运算符<< 调用父 ostream
【发布时间】:2016-01-13 12:10:04
【问题描述】:

代码:

cout << "11122333" << endl;

期待:
11122333\n
结果:
11122333\n
好的。
代码:

cout.operator<<("11122333");
cout.operator<<(endl);

期待:
11122333\n
结果:
00B273F8\n
(或其他地址,它被转换为void* :( )

问题: 想写从ostream派生的类

class SomeStream : public ostream
{
  public:
  explicit SomeStream(streambuf* sb) : ostream(sb) { }
  template <typename T> SomeStream &operator <<(const T &val) 
  {
    std::ostream::operator<<(val); //Trouble in there!
    std::cout << "<<" << " " << typeid(T).name() << " " << val << std::endl;
    /*some other behavior*/
    return *this;
  }
  SomeStream &operator <<(ostream& (*val) (ostream&))
  {
    std::ostream::operator<<(val);
    /*some other behavior*/
    return *this;
  }
  SomeStream &operator <<(ios_base& (*val) (ios_base&))
  {
    std::ostream::operator<<(val);
    /*some other behavior*/
    return *this;
  }
};

当我调用父操作员std::ostream::operator&lt;&lt;(val); val cast 为void* 并且不能正常工作。 怎么做才对?以及为什么为ostream 直接调用operator&lt;&lt; 与间接调用不同。

【问题讨论】:

标签: c++ operator-keyword ostream


【解决方案1】:

const char* 的输出 operator &lt;&lt; 不是 ostream 类型的成员。 Only those 重载是成员函数,其中之一是用于void*。 还有non-member overloads

有解决方法:

  template <typename T> SomeStream &operator <<(const T &val) 
  {
    static_cast<std::ostream&>(*this) << val; //Trouble in there!
    std::cout << "<<" << " " << typeid(T).name() << " " << val << std::endl;
    /*some other behavior*/
    return *this;
  }

【讨论】:

  • 只有static_cast&lt;ostream&amp;&gt;(*this) &lt;&lt; val; -> 工作。 static_cast&lt;std::ostream&gt;(*this) &lt;&lt; val; -> 不起作用 -> 错误 C2248: 'std::basic_ostream<_elem>::basic_ostream' : 无法访问类中声明的私有成员