比较 std::ostream 以查看它是否为 std::cout(“不匹配 'operator=='”)

0 c++ compiler-errors operators ostream

这个函数的功能是它将输出(到终端或文件,取决于作为参数传递给它的 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;
}
}
Run Code Online (Sandbox Code Playgroud)

0x4*_*2D2 6

您可以比较地址:

if (&os == &std::cout) {
  os << myStr.m_buffer << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

它将输出(根据作为参数传递给它的 ostream& os 对象的类型,输出到终端或文件)

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