c++ - 比较std::ostream to see if it is std::cout (“no match for ' operator= ='” )

标签 c++ compiler-errors operators ostream

该函数的功能是将MyString数据(保存在m_buffer中的C字符串表示形式)输出(到终端或文件,具体取决于作为参数传递给它的ostream&os对象的类型)。我收到一个编译器错误,指出“与'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;
}
}

最佳答案

您可以比较地址:

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

it will output(to terminal or file depending on the type of ostream& os object passed as a parameter to it)


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

关于c++ - 比较std::ostream to see if it is std::cout (“no match for ' operator= ='” ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60961046/

相关文章:

c++ - 将 std::string 插入到 std::fstream 中的任意位置

c++ - 在 C++ 文件中链接 mat.h

c - 我如何计算输出

php - PHP 中的 !== 比较运算符是什么意思?

java - Android Studio : lint to enforce '&&' instead of '&' ?

c++ - BB10 核心原生 SDK : Programmatically adjust screen brightness?

c++ - 如何将实时视频流从 YUV(HDYC) 转换为 RGB

c++ - 在这里使用指针 vector 是不必要的还是更糟,导致内存泄漏?

qt - Qt SDK问题

reactjs - 尝试安装 react-router-dom 时出现 npm 脚本错误