Reputation: 20179
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 (i.e. strings)!
Upvotes: 0
Views: 2557
Reputation: 179779
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. E.g.
MyString S("Hello");
if ("hello" == S) { // Can't use MyString::operator== here
std::cout << S;
}
Upvotes: 2
Reputation: 31435
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.
Upvotes: 2
Reputation: 14392
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)
Upvotes: 1