The functionality of this function is that it will output(to terminal or file depending on the type of ostream& os object passed as a parameter to it) the MyString data (the C-string representation held within m_buffer). I am receiving a compiler error that states that "no match for 'operator=='", specifically in the part of the code that states "if(os == std::cout)" Any suggestions? Thank you!
//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;
}
}
You can compare the addresses:
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
can also be a file stream since file streams also derived from std::ostream
/ std::istream
. So writing to os
will write to the terminal or file that the stream represents so there's really no need for the condition.
Because the std::ostream
class aka std::basic_ostream < char >
doesn't provide by any means comparison operators, and in general does not make sense to compare streams.
That said, a possible solution ( based on this answer ) is this
if( std::addressof( os ) == std::addressof( std::cout ) )
{
os << myStr.m_buffer << std::endl;
}
--
References:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.