ostream 运算符<<调用父 ostream

ostream operator<< call parent ostream

本文关键字:ostream lt 运算符 调用      更新时间:2023-10-16

代码:

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<<(val);时,val转换为void*,而不是正常工作。怎么做才对?以及CCD_ 6的直接呼叫CCD_。

const char*的输出operator <<不是类型ostream的成员。只有那些重载是成员函数,其中一个重载用于void*。还有非成员重载。

有一种变通方法:

  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;
  }