Three of the methods in the String
class perform comparisons. The operator<()
function returns true
if the first string comes before the second string alphabetically (or, more precisely, in the machine collating sequence). The simplest way to implement the string comparison functions is to use the standard strcmp()
function, which returns a negative value if its first argument precedes the second alphabetically, 0
if the strings are the same, and a positive value if the first follows the second alphabetically. So you can use strcmp()
like this:
bool operator<(const String &st1, const String &st2)
{
if (std::strcmp(st1.str, st2.str) < 0)
return true;
else
return false;
}
Because the built-in <
operator already returns a type bool
value, you can simplify the code further to this:
bool operator<(const String &st1, const String &st2)
{
return (std::strcmp(st1.str, st2.str) < 0);
}
Similarly, you can code the other two comparison functions like this:
bool operator>(const String &st1, const String &st2)
{
return st2 < st1;
}
bool operator==(const String &st1, const String &st2)
{
return (std::strcmp(st1.str, st2.str) == 0);
}
The first definition expresses the >
operator in terms of the <
operator and would be a good choice for an inline function.
Making the comparison functions friends facilitates comparisons between String
objects and regular C strings. For example, suppose answer
is a String
object and that you have the following code:
if ("love" == answer)
This gets translated to the following:
if (operator==("love", answer))
The compiler then uses one of the constructors to convert the code, in effect, to this:
if (operator==(String("love"), answer))
And this matches the prototype.
18.119.103.204