C++ 中“this”指针的目的是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2828841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:12:20  来源:igfitidea点击:

What is purpose of a "this" pointer in C++?

c++pointersthis

提问by de costo

What is purpose of thiskeyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a thisto call peer methods inside a class?

this关键字的目的是什么。一个类中的方法不能访问同一个类中的其他对等成员吗?什么需要调用 athis来调用类内的对等方法?

回答by Josh Kelley

Two main uses:

两个主要用途:

  1. To pass *thisor thisas a parameter to other, non-class methods.

    void do_something_to_a_foo(Foo *foo_instance);
    
    void Foo::DoSomething()
    {
        do_something_to_a_foo(this);
    }
    
  2. To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.
    MessageBox::MessageBox(const string& message)
    {
      this->message = message;
    }
    (Although an initialization listis usually preferable to assignment in this particular example.)
  1. 传递*thisthis作为参数传递给其他非类方法。

    void do_something_to_a_foo(Foo *foo_instance);
    
    void Foo::DoSomething()
    {
        do_something_to_a_foo(this);
    }
    
  2. 允许您消除成员变量和函数参数之间的歧义。这在构造函数中很常见。
    MessageBox::MessageBox(const string& message)
    {
      this->message = message;
    }
    (尽管在此特定示例中,初始化列表通常比赋值更可取。)

回答by Martin York

  • Helps in disambiguating variables.
  • Pass yourself as a parameter or return yourself as a result
  • 有助于消除变量的歧义。
  • 将自己作为参数传递或作为结果返回自己

Example:

例子:

struct A
{
    void test(int x)
    {
        this->x = x;                 // Disambiguate. Show shadowed variable.
    }
    A& operator=(A const& copy)
    {
        x = copy.x;
        return *this;                // return a reference to self
    }

    bool operator==(A const& rhs) const
    {
         return isEqual(*this, rhs); // Pass yourself as parameter.
                                     // Bad example but you can see what I mean.
    }

    private:
        int x;
};

回答by Justin Ethier

Consider the case when a parameter has the same name as a class member:

考虑参数与类成员同名的情况:

void setData(int data){
  this->data = data;
}

回答by dlb

The expression *thisis commonly used to return the current object from a member function:

该表达式*this通常用于从成员函数返回当前对象:

return *this;

The thispointer is also used to guard against self-reference:

this指针也被用来防止自我参考:

if (&Object != this) {
// do not execute in cases of self-reference

回答by JohnMcG

  1. Resolve ambgiguity between member variables/functions and those defined at other scopes
  2. Make explicit to a reader of the code that a member function is being called or a member variable is being referenced.
  3. Trigger IntelliSense in the IDE (though that may just be me).
  1. 解决成员变量/函数与在其他范围定义的成员变量/函数之间的歧义
  2. 向代码的读者明确说明正在调用成员函数或正在引用成员变量。
  3. 在 IDE 中触发 IntelliSense(虽然这可能只是我)。

回答by Mohit Jain

Some points to be kept in mind

需要牢记的一些要点

  • This pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.

  • This pointer is not counted for calculating the size of the object.

  • This pointers are not accessible for static member functions.

  • This pointers are not modifiable

  • 该指针存储类实例的地址,使成员能够通过指针访问类的成员函数。

  • 计算对象的大小时不计算该指针。

  • 静态成员函数无法访问此指针。

  • 此指针不可修改

Look at the following example to understand how to use the 'this' pointer explained in this C++ Tutorial.

查看以下示例以了解如何使用本 C++ 教程中解释的“this”指针。

class this_pointer_example // class for explaining C++ tutorial 
{
    int data1;
 public:
    //Function using this pointer for C++ Tutorial
    int getdata()
    { 
        return this->data1;
    } 
  //Function without using this pointer 
  void setdata(int newval)
  {
       data1 = newval;
  }
};

Thus, a member function can gain the access of data member by either using this pointer or not. Also read thisto understand some other basic things about this pointer

因此,成员函数可以通过使用或不使用此指针来获取数据成员的访问权限。另请阅读本文以了解有关此指针的其他一些基本内容

回答by Eclipse

It lets you pass the current object to another function:

它允许您将当前对象传递给另一个函数:

class Foo;

void FooHandler(Foo *foo);

class Foo
{
    HandleThis()
    {
       FooHandler(this);
    }  
};

回答by Notinlist

For example if you write an operator=()you must check for self assignment.

例如,如果你写了一个operator=()你必须检查自赋值。

class C {
public:
    const C& operator=(const C& rhs)
    {
        if(this==&rhs) // <-- check for self assignment before anything
            return *this;
        // algorithm of assignment here
        return *this; // <- return a reference to yourself
    }
};

回答by LukeN

The thispointer inside a class is a reference to itself. It's needed for example in this case:

this类内的指针是对自身的引用。例如在这种情况下需要它:

class YourClass
{
   private:
      int number;

   public:
      YourClass(int number)
      {
         this->number = number;
      }
}

(while this would have been better done with an initialization list, this serves for demonstration)

(虽然这最好用初始化列表来完成,但这只是为了演示)

In this case you have 2 variables with the same name

在这种情况下,您有 2 个具有相同名称的变量

  1. The class private "number"
  2. And constructor parameter "number"
  1. 班级私人“号码”
  2. 和构造函数参数“编号”

Using this->number, you let the compiler know you're assigning to the class-private variable.

使用this->number,您可以让编译器知道您正在分配给类私有变量。

回答by Ignacio Vazquez-Abrams

It allows you to get around members being shadowed by method arguments or local variables.

它允许您绕过被方法参数或局部变量遮蔽的成员。