Overloaded operators calling each other.
Hello peoples.
I'm just learning about C++ classes, and overloading operators. I'm having some trouble with two overloads, one of which is operator==(char * ), and the other one is operator==(const CStr&).
Both of these methods contain the exact same code, with the only difference is that one takes a pointer to a character array, while the other one takes a class instance. I would like to be able to call the operator== that takes the character array from within the class instance method, to cut down on code.
Class Calls (Both of which are public):
int operator==( char *);
int operator==(const CStr&);
Method for == "String", same code for Class instance:
int CStr::operator ==(char * pIncomingString)
{
int Match = 1;
int Counter = 0;
while (Counter < Next && Match != 0)
{
if (*(pIncomingString + Counter) == Text[Counter++])
Match = 1;
else
Match = 0;
}
return Match;
}
From within the method with the class instance, I have tried a variety of lines to try to call this, but so far either it doesn't work at all, or it errors out.
operator==(IncomingClass.Text);
I have been working with this line, but no luck. I've tried to do Text==(IncomingClass.Text). This line will compile fine, but does not give me the expected results.
This code is for a project, which is complete, but am curious why I cannot call correctly another method and reduce duplicate code.
Thanks
-Jeff
Re: Overloaded operators calling each other.
Quote:
Originally posted by SphereII
Hello peoples.
I'm just learning about C++ classes, and overloading operators. I'm having some trouble with two overloads, one of which is operator==(char * ), and the other one is operator==(const CStr&).
1) Why isn't it operator(const char *)? You aren't changing the value of the pointed to character buffer, so this should be const char *.
2) Do you have any casting operators, for example an overload of operator char *() defined in your class? If you do, then I can see a boatload of compile problems. If this is the case, get rid of these casting operators and try again. The reason these operators are problematic is that you are making the compiler do twists and turns whenever it sees a char * and a CStr in the same contexts.
3) Tell us exactly the errors you're getting (post the actual compile error). Don't just say "it errors out" (and please post the error you received before you tried AssMaster's code).
4) Next time, post your full code so we can see exactly what you are trying to do. With C++, the code that you don't show is more than not, the cause of the problem.
Regards,
Paul McKenzie