gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:49:12 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com