在this关键字上调用函数

use*_*276 5 c++ function this

所以在我的头文件中,我将这两个变量声明为private

private:

    char* data;

    int len;
Run Code Online (Sandbox Code Playgroud)

并让它访问它

int length() const { return len; }
Run Code Online (Sandbox Code Playgroud)

然后在我的cpp文件中,我试图覆盖字符串实现中的运算符,如下所示:

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;
 }
Run Code Online (Sandbox Code Playgroud)

当我编译这个时,我收到此错误:

mystring.cpp:263:14:错误:请求'this'中的成员'length',这是非类型'MyString*const'

从我可以通过尝试调用.length()on 来判断这是尝试访问此指针上的变量,这导致问题,就像在这个问题中.

那很好,因为我可以这样做:

 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;
 }
Run Code Online (Sandbox Code Playgroud)

编译很好,但现在我想知道如何在这个指针上调用一个函数.我认为,因为它是一个指针,我必须先取消引用它,所以我尝试了这个:

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;
 }
Run Code Online (Sandbox Code Playgroud)

但我又得到了这个错误:

mystring.cpp:273:17:错误:请求'this'中的成员'length',这是非类型'MyString*const'

看起来这应该工作得很好,因为我会将指针解引用到它所指向的对象确实有那个方法,但我似乎错过了一些东西.我如何在this指针上调用类中定义的函数?是否有一些功能性的原因,为什么我上面描述的方式不起作用?

rav*_*avi 7

if((this.length()) > (string.length())){
Run Code Online (Sandbox Code Playgroud)

这应该是

if((this->length()) > (string.length())){
Run Code Online (Sandbox Code Playgroud)

作为一个指针.this基本上this只是一个指针,指向调用成员函数的对象.因此,您必须使用->该类的所有成员的引用.

还有一个建议是停止使用标准关键字的变量名称.喜欢string你的情况.如果你包含std命名空间,你就有理由不这样做.