c++ - 在 this 关键字上调用函数

标签 c++ function this

所以在我的头文件中我将这两个变量声明为私有(private)

private:

    char* data;

    int len;

并给它访问它

int length() const { return len; }

然后在我的 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;
 }

当我编译这个时我得到这个错误:

mystring.cpp:263:14: error: request for member ‘length’ in ‘this’, which is of non-class type ‘MyString* const’

据我所知,通过尝试调用 this 上的 .length() 试图访问 this 指针上的变量,这导致了问题,例如 this question .

没关系,因为我可以这样做:

 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;
 }

编译正常,但现在我想知道如何在 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;
 }

但是我又遇到了这个错误:

mystring.cpp:273:17: error: request for member ‘length’ in ‘this’, which is of non-class type ‘MyString* const’

这似乎应该可以正常工作,因为我会取消引用指向它指向的对象的指针,该对象确实具有该方法,但我似乎遗漏了一些东西。我将如何在 this 指针上调用我的类中定义的函数?是否有一些功能性原因导致我上面描述的方法不起作用?

最佳答案

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

应该是

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

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

还有一个建议停止使用作为标准关键字的变量名。就像你的例子中的 string 一样。如果您包含了 std 命名空间,您就会找到不这样做的理由。

关于c++ - 在 this 关键字上调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27087477/

相关文章:

c++ - 指向指针数组的指针理解问题

C++ 链接器错误 undefined reference to `Suma(int, int)' ld returned 1 exit status

javascript - 为什么这个函数没有运行?

javascript - 我们如何证明javascript函数是对象?

c++ - 非类型模板参数的用户定义推导指南

c++ - lua_getglobal 崩溃程序

c - 结构体函数的传递和返回

javascript - nodejs全局变量是否绑定(bind)到 "module"函数,如何赋值?

Jquery $this 或each() 一次指定一个链接

java - C++,使用它从自身调用构造函数