KL wrote:
> hbsk wrote:
>
>>when an statement like (a < b) is invoked, it expands to the
>>following: a.operator<(b); ie, operator < is invoked for object a
>>passing object b as the parameter. hence you don't have to worry
>>about object a ( provided a and b are objects of the same
>>type/class/struct/union).that is also the reason you have only one
>>parameter in the overloaded function.
>
>
> I am still a bit confused. I don't know why I can't grasp this. Here is
> what I have so far:
I assume this is part of a definition for a class STRING, but you're
missing the beginning:
class STRING {
> STRING(string s){
>
There's really no reason to pass the ctor parameter s by value as this
will require making a duplicate copy lasting only for the duration of
the constructor execution. Try, STRING (const string& s)
> int a;
>
> for (a=0; a<100; a++)
>
> letters[a] = ' ';
Indenting your code will make it easier for others (and you!) to read...
>
> a = 0;
>
> length = s.length();
>
> while (a < length) {
>
> letters[a] = s.at(a);
>
> a++;}
Is letters an array of size 100? If so, this is a risky bit of code if
s is longer than that.
>
> };
If I've counted correctly, the above } closes the ctor definition and
should not be followed by a semicolon.
>
> bool operator<(const STRING&) const;
OK, so you've declared a const member function operator<. Looks good.
>
> };
>
> bool operator<(const STRING& b) const {
>
> for (int a=0;a<100;a++){
>
> return (s.letters[a]<b.letters[a];
>
> }
>
> }
OK, there are a couple problems here. First, your function definition
needs its name fully qualified. This should be:
bool STRING:

perator<(const STRING& b) const {
Because the fcn definition is not placed inside the STRING class
definition, the compiler doesn't know that this is a member function of
STRING as opposed to any other class with a < operator.
Fixing that will probably make your code compile (I can't say for sure
since you've left out other parts of the STRING class definition such as
the definition of the array letters) but it probably won't do what you
want it to do. Your for loop will only be executed once because on its
first iteration it encounters a return statement and that's the end of
that. You probably want to check if the characters are equal and if so
move on to the next character before returning a result. Consider aaa <
azz, for example.
Also you need to be careful when comparing characters by value. For
example, it may be that capital Z is less than lowercase a. Is that
what you want? Also I'm not sure about this, but I don't know that
there's any guarantee that a < b < c < ... < z. Perhaps someone who
knows these fine details better than I do can comment on this.
>
>
> I get the feeling that this is not completely correct. Any insights?
Yeah. See above
Hope that helps,
Mark