Więc w moim pliku nagłówka I te dwie zmienne zadeklarowane jako prywatnyWywołanie funkcji na tego słowa kluczowego
private:
char* data;
int len;
i dać to do niego dostęp
int length() const { return len; }
potem w moim pliku cpp jestem próbując przesłonić operatorów w implementacji łańcuchowej w ten sposób:
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;
}
kiedy skompiluję ten błąd, otrzymuję ten błąd:
mystring.cpp:263:14: error: request for member ‘length’ in ‘this’, which is of non-class type ‘MyString* const’
Z tego co mogę powiedzieć, próbując wywołać .length()
na ten próbuje uzyskać dostęp do zmiennej o tym wskaźnikiem, który jest przyczyną problemu, jak w this question.
To dobrze, bo mogę to zrobić w zamian:
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;
}
który kompiluje w porządku, ale teraz zastanawiam się jak można wywołać funkcję na tym wskaźniku. Pomyślałem, że ponieważ był to wskaźnik musiałbym dereference najpierw więc próbowałem to:
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;
}
Ale znowu mam ten błąd:
mystring.cpp:273:17: error: request for member ‘length’ in ‘this’, which is of non-class type ‘MyString* const’
Wydaje się, że powinno to działało dobrze jak Odsunąłbym wskaźnik na obiekt, na który wskazywał, który rzeczywiście ma tę metodę, ale wydaje mi się, że czegoś mi brakuje. W jaki sposób chciałbym wywołać funkcję zdefiniowaną w mojej klasie na wskaźniku this
? I czy istnieje jakiś powód funkcjonalny, dlaczego sposób opisany powyżej nie działa?
'this-> length()'. Lub po prostu 'length()'. – juanchopanza
'(* this) .length' również będzie działało, chociaż jest bardziej szczegółowe niż' -> '. Niestety twoja '* (this) .length' jest analizowana jako' * (this.length) 'i dlatego nie działa. –
Och, dziękuję za wskazanie, że – user3282276