【发布时间】: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