Function call for this keyword

So, in my header file, these two variables are declared private

private: char* data; int len; 

and give him access to him

 int length() const { return len; } 

Then, in my cpp file, I try to override the operators in the string implementation as follows:

 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 the length of a member in 'this, which does not belong to the class' MyString * const

From what I can say, trying to call .length() , it is trying to access the variable on this pointer, which causes the problem, for example, in this question .

This is great because I can do it 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 you call the function on this pointer. I thought that since it was a pointer, I would first have to play it, 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: query for the length of a member in 'this, which is of the nonclass type' MyString * const

It seems that this should work fine, as I would dereference the pointer to the object that it was pointing to, which really has this method, but it seems to me that something is missing. How do I access a function defined in my class in the this pointer? And is there any functional reason why the method described above does not work?

+5
source share
1 answer
 if((this.length()) > (string.length())){ 

It should be

 if((this->length()) > (string.length())){ 

as this is a pointer. Typically, this is just a pointer that references the object that the member function is being called on. Therefore, you should use -> for all references to members of this class.

Another tip is to stop using variable names, which are standard keywords. like string in your case. If you included the std namespace, you would have a reason not to.

+6
source

Source: https://habr.com/ru/post/1207512/


All Articles