该函数的功能是将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/