I noticed that many string classes in C++ doesn't implement the ==
operator to compare to strings. What is the reason behind that? As far as I can see, implementing a class for a string is supposed to make the string an entity by itself, rather than a pointer to a set of characters. So we should definitely expect the ==
operator to be implemented to compare the values of two entities (ie strings)!
std::string is basic_string and it does have operator==, which uses the compare method of char_traits.
You can even put in a specialist traits class of your own to do case-insensitive comparison.
Often, when a class doesn't implement operator==
, it's because there's a free function outside the class. The advatnage of a free function operator==
is that it supports implicit conversions on both sides. This is especially important for strings, because there you often use const char[]
literals and want that implicit conversion. Eg
MyString S("Hello");
if ("hello" == S) { // Can't use MyString::operator== here
std::cout << S;
}
A reason for not implementing operator== for a string class would be if you believe that there are more ways to compare strings: case sensitive/insensitive, ignore accents,... and you provide different compare functions to let the user specify.
It is still a choice and as Jeff Foster already commented: it is implemented in the only real string in C++ (std::string)
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.