Operators may not be overloaded for built-in types, for reasons that are
fairly clear if you pause to consider the implications.
In this case, you are attempting to fundamentally change the meaning of the
expression. You might think of char* as a "string", but C++ thinks of it as
a pointer. s1 == s2 compares the address values contained in the pointer
itself, not the strings they point to. You are asking it for a radical
change in behavior. Consider the potential for mischief allowing this sort
of thing would cause. C++ already has enough minefields. The whole point of
operator overloading is to make the resulting code more clear in its
intent. Your attempt not only obfuscates the resulting code, since you are
actually attempting to compare not the pointers but the null-terminated
char arrays they reference, and furthermore lays a booby-trap for anybody
hoping to maintain the code thereafter who foolishly assumes they can tell
if two variables are pointing to the same location by using the == operator.
And so, such things are illegal. It is allowed for custom types, since
there are no preexisting assumptions about how such types should behave as
there would be with, say, int or bool. Even so, operator overloading used
to excess can quickly make code practically unmaintainable.
You need to use a string class with the (char *) and == operators
overloaded in the way you desire. The standard library already provides
such a class, std::String. You can do exactly what you want with no
further coding required like so: String( s1) == String( s2 ). Of course,
using String to hold your strings in the first place would eliminate a lot
of temporaries. I question what you would be accomplishing by the foregoing
maneuver.
Or, you could make your own lightweight struct with the necessary operators
and constructors. But honestly, if you can't or don't want to use
std::String from the start, is reading strcmp really so bad? Why confuse
the situation and introduce potential bugs and maintenance headaches just
so you can use == and save a few keystrokes? If the use of a real string
class is unpalatable, I strongly suggest sticking with the strcmp method,
since anybody reading it will most certainly understand what is going on,
whereas your attempts at operator magic will likely just confuse the
situation. Refactor when it produces a measurable benefit, not just because
you can. If you must refactor this code, refactor to use std::String
instead of char* altogether, rather than just worrying about the compare
operation.
--- Kevin
|