The Relational Operators. McGraw-Hill The Complete Reference Fourth Edition
โฆษณา
โฆษณา
C h a p t e r 3 9 : I n t e g r a t i n g N e w C l a s s e s : A C u s t o m S t r i n g C l a s s
947
The Relational Operators
The StrType class supports the full range of relational operations to be applied to strings. The overloaded relational operators are defined within the StrType class declaration. They are repeated here for your convenience:
// relational operations between StrType objects int operator==(StrType &o) { return !strcmp(p, o.p); } int operator!=(StrType &o) { return strcmp(p, o.p); } int operator<(StrType &o) { return strcmp(p, o.p) < 0; } int operator>(StrType &o) { return strcmp(p, o.p) > 0; } int operator<=(StrType &o) { return strcmp(p, o.p) <= 0; } int operator>=(StrType &o) { return strcmp(p, o.p) >= 0; }
// operations between StrType objects and quoted strings int operator==(char *s) { return !strcmp(p, s); } int operator!=(char *s) { return strcmp(p, s); } int operator<(char *s) { return strcmp(p, s) < 0; } int operator>(char *s) { return strcmp(p, s) > 0; } int operator<=(char *s) { return strcmp(p, s) <= 0; } int operator>=(char *s) { return strcmp(p, s) >= 0; }
The relational operations are very straightforward; you should have no trouble understanding their implementation. However, keep in mind that the StrType class implements comparisons between two StrType objects or comparisons that have a
StrType
object as the left operand and a quoted string as the right operand. If you want to be able to put the quoted string on the left and a StrType object on the right, you will need to add additional relational functions.
Given the overloaded relational operator functions defined by StrType, the following types of string comparisons are allowed:
StrType x("one"), y("two"), z("three"); if(x < y) cout << "x less than y"; if(z=="three") cout << "z equals three"; y = "o"; z = "ne"; if(x==(y+z)) cout << "x equals y+z";
ดาวน์โหลด
โฆษณา