我什么时候应该明确使用 \`this\` 指针?

新手上路,请多包涵

我什么时候应该在类的方法中明确写 this->member

原文由 user53670 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 769
2 个回答

通常,您不必这样做,暗示 this->

有时,存在名称歧义,可用于消除类成员和局部变量的歧义。但是,这是一个完全不同的情况,其中明确需要 this->

考虑以下代码:

 template<class T>
struct A {
   T i;
};

template<class T>
struct B : A<T> {
    T foo() {
        return this->i; //standard accepted by all compilers
        //return i; //clang and gcc will fail
        //clang 13.1.6: use of undeclared identifier 'i'
        //gcc 11.3.0: 'i' was not declared in this scope
        //Microsoft C++ Compiler 2019 will accept it
    }

};

int main() {
    B<int> b;
    b.foo();
}

如果省略 this-> ,一些编译器不知道如何处理 i 。 In order to tell it that i is indeed a member of A<T> , for any T , the this-> prefix is required.

注意:仍然可以使用以下命令省略 this-> 前缀:

 template<class T>
struct B : A<T> {
    int foo() {
        return A<T>::i; // explicitly refer to a variable in the base class
        //where 'i' is now known to exist
    }

};

原文由 ASk 发布,翻译遵循 CC BY-SA 4.0 许可协议

this 指针的主要(或者我可以说是唯一的)目的是它指向用于调用成员函数的对象。

基于这个目的,我们可以有一些情况,只有使用 this 指针才能解决问题。

例如,我们必须在成员函数中返回调用对象,参数是同一个类对象:

 class human {

...

human & human::compare(human & h){
    if (condition)
        return h;       // argument object
    else
        return *this;   // invoking object
    }
};

原文由 Van Tr 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题