【问题标题】:Compare std::ostream to see if it is std::cout ("no match for 'operator=='")比较 std::ostream 是否为 std::cout ("no match for 'operator=='")
【发布时间】:2020-07-12 14:55:42
【问题描述】:

此函数的功能是输出(到终端或文件,具体取决于作为参数传递给它的 ostream 和 os 对象的类型)MyString 数据(保存在 m_buffer 中的 C 字符串表示形式)。我收到一个编译器错误,指出“'operator==' 不匹配”,特别是在代码部分显示“if(os == std::cout)”有什么建议吗?谢谢!

//in header file
friend std::ostream & operator<<(std::ostream & os, const MyString & myStr);

//in cpp file
bool MyString::operator==(const MyString & other)const{
if(strcmp(m_buffer,other.m_buffer) == 0){
    return true;
}else if (strcmp(m_buffer,other.m_buffer) != 0){
    return false;
}
}

std::ostream& operator<<(std::ostream& os, const MyString& myStr){
  if(os == std::cout){
  os << myStr.m_buffer << std::endl;
}
}

【问题讨论】:

  • 你为什么要这个逻辑?这对我来说没有意义。
  • 注意:std::cout 被声明(在 中)作为一个 basic_ostream 对象。因此,仅通过继承,std::cout 就是一个 std::ostream。布尔测试是不必要的。

标签: c++ compiler-errors operators ostream


【解决方案1】:

您可以比较地址:

if (&os == &std::cout) {
  os << myStr.m_buffer << std::endl;
}

它将输出(到终端或文件,具体取决于作为参数传递给它的 ostream 和 os 对象的类型)

os 也可以是文件流,因为文件流也派生自 std::ostream/std::istream。因此,写入os 将写入流所代表的终端或文件,因此实际上不需要条件。

【讨论】:

    【解决方案2】:

    因为std::ostream 类又名std::basic_ostream &lt; char &gt; 不提供任何比较运算符,并且通常比较流没有意义。

    也就是说,一个可能的解决方案(基于this answer)是这样的

    if( std::addressof( os ) == std::addressof( std::cout ) )
      {
        os << myStr.m_buffer << std::endl;
      }
    

    --

    参考资料:

    https://en.cppreference.com/w/cpp/io/basic_ostream

    https://en.cppreference.com/w/cpp/memory/addressof

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2012-10-20
      • 2010-09-26
      • 1970-01-01
      • 2013-07-28
      • 2010-12-10
      相关资源
      最近更新 更多