views:

491

answers:

2

I'm building a comparator for an assignment, and I'm pulling my hair out because this seems to simple, but I can't figure it out.

This function is giving me trouble:

int compare(Word *a, Word *b)
{
    string *aTerm = a->getString();
    string *bTerm = b->getString();

    return aTerm->compare(bTerm);
}

Word::getString returns a string*

Error:

 In member function `virtual int CompWordByAlpha::compare(Word*, Word*)':   
  no matching function for call to...

...followed by a bunch of function definitions.

Any help?

+5  A: 

You're comparing a string to a string pointer, and that's not valid. You want

   return aTerm->compare(*bTerm);
Fred Larson
That did it. I don't understand why the asterisk was required, as bTerm is already a *string. Does that mean the basic_string::compare method requires a **basic_string parameter?
Mike
string::compare() takes a string reference as a parameter, not a pointer. Passing *bTerm dereferences the pointer so that you pass a string object, not a string pointer.
Fred Larson
Oh, that makes perfect sense. Thanks Fred!
Mike
You're welcome! Glad to help.
Fred Larson
+3  A: 

You aren't getting the different uses of the * operator. The use of the * in "string* bTerm = b->getString()" means "bTerm is a pointer to a string". The use of the * inside of compare(*bTerm) means "take the value of the location pointed to by bTerm" instead of just using compare(bTerm) which simply attempts to compare the value of bTerm itself, which is a hex address.

This is also happening on the left side of that call:

aTerm->compare(*bTerm); //this statement
(*aTerm).compare(*bTerm); //is the same as this statement

The -> operator just reduces the amount of typing required.

P.S.: This kind of stuff you could have easily figured out from Google or your programming textbook. Although others may disagree, I don't feel that questions about completely basic syntax have any place on Stack Overflow.

muusbolla
I learned Java first and I'm just starting C++, so I'm still getting used to having to consciously manage pointers and references. I found Fred's answer extremely helpful for getting my program to compile, and I found yours extremely informative.Now, how do I print output?;)
Mike
You print output with std::cout.
Max Lybbert