为什么我们使用"this"指针? [英] Why do we use 'this' pointer?

查看:123
本文介绍了为什么我们使用"this"指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,如果可以在对象的帮助下简单地调用类的成员函数,那么为什么需要使用"this"指针呢?

What is the need of ''this'' pointer in this example, if we can simply call the member function of the class with the help of objects then why we use ''this'' pointer?

#include <iostream> 
using namespace std; 
 
class MyClass { 
  int i; 
public: 
  void setI(int val) { 
    this->i = val; 
  }  
  int getI() { 
    return this->i; 
  }  
} ; 
  

int main() 
{ 
  MyClass o; 
 
  o.setI(100); 
  cout << o.getI(); 
 
  return 0; 
}

推荐答案

在您的示例中,您不需要this.
但是:
In your example you dont need this.
But:
class CRect : protected RECT
{
public:
  CRect(RECT& rcinit){ CopyRect(this,&rcinit); }

  operator RECT& (){ return *this; }
};


这是一个简单的示例,您需要this.
问候.


Is a simple example you need this.
Regards.


我们有时使用this来消除变量之间的混淆.

例如:

we use this to sometimes remove confusions between variables.

for example :

class MyClass
{
  void foo();
  int i;
};

void MyClas::foo()
{
  int i;
  i = i; // confused ?
  i = this->i; // less confused ?

}


大多数时候,您不需要这样做.您只需要真正使用this来精确指定要使用的两个同名变量中的哪个:本地/参数1或类级别/实例1.在这种情况下,使用this会强制识别类级别的变量,缺少它会导致使用局部变量或参数变量.

如果没有名称冲突.那么您就不需要使用this,因为编译器会自动将其插入.但是,如果您这样做,那不是一个错误-不必要,不整洁并且有点学习者"-但这不是一个错误! :laugh:
Most of the time, you don''t need to. You only really need to use this to specify exactly which of two identically named variables you mean: the local / parameter one, or the class level / instance one. When you have this situation, using this forces recognition of class level variable, lack of it infers use of the local or parameter variable.

If there is no name conflict. then you don''t need to use this, as the compiler will automatically insert it. But if you do, it''s not an error - unnecessary, untidy and a bit "learner" - but not an error! :laugh:


这篇关于为什么我们使用"this"指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆