So in my header file I have these two variables declared as private
private:
char* data;
int len;
and give this to access it
int length() const { return len; }
Then in my cpp file I am trying to override the operators in string implementation like this:
bool MyString::operator>(const MyString& string)
{
//Compare the lengths of each string
if((this.length()) > (string.length())){
return 0;
}
//The given string is shorter
return -1;
}
when I compile this I get this error:
mystring.cpp:263:14: error: request for member ‘length’ in ‘this’, which is of non-class type ‘MyString* const’
From what I can tell by trying to call the .length()
on the this is trying to access a variable on the this pointer which is causing a problem, like in this question.
That's fine because I can do this instead:
bool MyString::operator>(const MyString& string)
{
//Compare the lengths of each string
if((this->len) > (string.length())){
return 0;
}
//The given string is shorter
return -1;
}
which compiles fine but now I'm wondering how do you call a function on a this pointer. I thought that because it was a pointer I would have to dereference it first so I tried this:
bool MyString::operator>=(const MyString& string)
{
//Compare the lengths of each string
if((*(this).length()) >= (string.length())){
return 0;
}
//The given string is shorter but not equal
return -1;
}
But again I got this error:
mystring.cpp:273:17: error: request for member ‘length’ in ‘this’, which is of non-class type ‘MyString* const’
It seems like this should have worked fine as I would have dereferenced the pointer into the object it pointed to which does indeed have that method but I seem to be missing something. How would I go about calling a function defined in my class on the this
pointer? And is there some functional reason why the way I described above does not work?
if((this.length()) > (string.length())){
This should be
if((this->length()) > (string.length())){
as this
is a pointer.Basically this
is just a pointer referring to the object on which member function is called. So, you have to use ->
for all reference to members of that class.
One more advice stop using variable names which are standard keywords. like string
in your case. Had you included std namespace you would have got the reason for not doing so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With