Comparison Operator Overloading
I have created a class for which I would like to overload the == operator. The name of the class is String. The problem I am running into comes into play when the object is a pointer..
String *a = new String();
if (a == "") return true; //error in VC++
the following operators are defined in the string class..
class String
{
bool operator ==(char *);
friend bool operator==(String &, char *);
}
I tried adding:
friend bool operator==(String *, char *);
but I get a compiler error.. What to do?
Using operator == for string comparison is BAD
It is a BAD idea to use == operator for string comparison. The reason is obvious:
if (mystring == "hello world!") {//...}
Why it is bad? There is ambiguity exactly what do you mean two strings are "equal"? It is unfortunate that alphabets of most languages have lower case and upper case. When comparing two strings, some times case doesn't matter, some times you do care about the case. Using a "==" buries that information and leaves ambiguity there.
It is better to use traditional strcmp, stricmp, strncmp etc.
Re: Using operator == for string comparison is BAD
Quote:
Originally posted by Anthony Mai
It is a BAD idea to use == operator for string comparison. The reason is obvious:
if (mystring == "hello world!") {//...}
Why it is bad? There is ambiguity exactly what do you mean two strings are "equal"?
The ambiguity is when someone is creating home-made classes and there is no written rules as to what is meant by "==".
For std::string, operator == is well defined -- the comparison is done lexicographically according to the current character traits ("The C++ Standard Library", Josuttis, 11.2.7).
Regards,
Paul McKenzie