C++ “this”指针是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16492736/
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-27 20:24:16  来源:igfitidea点击:

What is the 'this' pointer?

c++classpointersthis

提问by user2371809

I'm fairly new to C++, and I don't understand what the thispointer does in the following scenario:

我对 C++ 相当陌生,我不明白this指针在以下场景中的作用:

void do_something_to_a_foo(Foo *foo_instance);


void Foo::DoSomething()
{
  do_something_to_a_foo(this);
}

I grabbed that from someone else's post on here.

我从这里的其他人的帖子中抓住了这一点。

What does thispoint to? I'm confused. The function has no input, so what is thisdoing?

this指向什么?我糊涂了。该函数没有输入,那么在this做什么呢?

回答by TelKitty

thisrefers to the current object.

this指向当前对象。

The keyword thisidentifies a special type of pointer. Suppose that you create an object named xof class A, and class Ahas a non-static member function f(). If you call the function x.f(), the keyword thisin the body of f()stores the address of x.

关键字this标识了一种特殊类型的指针。假设您创建了一个名为xof的对象class A,并且class A有一个非静态成员函数f()。如果调用该函数x.f()this则主体中的关键字f()存储的地址x

回答by Nik Bougalis

The short answer is that thisis a special keyword that identifies "this" object - the one on which you are currently operating. The slightly longer, more complex answer is this:

简短的回答是,这this是一个特殊的关键字,用于标识“这个”对象 - 您当前正在操作的对象。稍微长一点,更复杂的答案是这样的:

When you have a class, it can have member functions of two types: staticand non-static. The non-staticmember functions must operate on a particular instanceof the class, and they need to know where that instance is. To help them, the language defines an implicit variable (i.e. one that is declared automatically for you when it is needed without you having to do anything) which is called thisand which will automatically be made to point to the particular instance of the class on which the member function is operating.

当你有 a 时class,它可以有两种类型的成员函数:static和 非static。非static成员函数必须对类的特定实例进行操作,并且它们需要知道该实例在哪里。为了帮助他们,语言定义的隐含变量(即一个是在需要时,您无需做任何事情为你自动声明),它被称为this和将自动变为指向类的特定实例上成员函数正在运行。

Consider this simple example:

考虑这个简单的例子:

#include <iostream>

class A
{
public:
    A() 
    { 
        std::cout << "A::A: constructed at " << this << std::endl;
    } 

    void SayHello()
    {
        std::cout << "Hi! I am the instance of A at " << this << std::endl;
    }
};

int main(int, char **)
{
    A a1;
    A a2;

    a1.SayHello();        
    a2.SayHello();

    return 0;
}

When you compile and run this, observe that the value of thisis different between a1and a2.

当您编译并运行它时,请注意和this之间的 值不同。a1a2

回答by jxh

Just some random facts about thisto supplement the other answers:

只是一些关于this补充其他答案的随机事实:

class Foo {
public:
    Foo * foo () { return this; }
    const Foo * cfoo () const { return this; /* return foo(); is an error */ }
};

Foo x;       // can call either x.foo() or x.cfoo()
const Foo y; // can only call x.cfoo()

When the object is const, the type of thisbecomes a pointer to const.

当对象为 时const, 的类型this变为指向 的指针const



class Bar {
    int x;
    int y;
public:
    Bar () : x(1), y(2) {}
    void bar (int x = 3) {
        int y = 4;
        std::cout << "x: " << x << std::endl;
        std::cout << "this->x: " << this->x << std::endl;
        std::cout << "y: " << y << std::endl;
        std::cout << "this->y: " << this->y << std::endl;
    }
};

The thispointer can be used to access a member that was overshadowed by a function parameter or a local variable.

this指针可用于访问,是由一个功能参数或局部变量盖过的部件。



template <unsigned V>
class Foo {
    unsigned v;
public:
    Foo () : v(V) { std::cout << "<" << v << ">" << " this: " << this << std::endl; }
};

class Bar : public Foo<1>, public Foo<2>, public Foo<3> {
public:
    Bar () { std::cout << "Bar this: " << this << std::endl; }
};

Multiple inheritance will cause the different parents to have different thisvalues. Only the first inherited parent will have the same thisvalue as the derived object.

多重继承会导致不同的父级具有不同的this值。只有第一个继承的父this对象与派生对象具有相同的值。

回答by AngelCastillo

thisis a pointer to self (the object who invoked this).

this是一个指向 self (调用this的对象)的指针。

Suppose you have an object of class Car named car which have a non static method getColor(), the call to this inside getColor() returns the adress of car (the instance of the class).

假设您有一个名为 car 的类 Car 对象,它有一个非静态方法 getColor(),在 getColor() 内部调用 this 返回 car 的地址(类的实例)。

Static member functions does not have a thispointer(since they are not related to an instance).

静态成员函数没有this指针(因为它们与实例无关)。

回答by Tooba Iqbal

this means the object of Foo on which DoSomething() is invoked. I explain it with example

这意味着调用 DoSomething() 的 Foo 对象。我用例子来解释

void do_something_to_a_foo(Foo *foo_instance){
    foo_instance->printFoo();
}

and our class

还有我们班

class Foo{
    string fooName;
    public:
        Foo(string fName);
        void printFoo();
        void DoSomething();
};

Foo::Foo(string fName){
     fooName = fName;
}
void Foo::printFoo(){
      cout<<"the fooName is: "<<fooName<<endl;
}
void Foo::DoSomething(){
     do_something_to_a_foo(this);
}

now we instantiate objects like

现在我们实例化对象,如

Foo fooObject("first);
f.DoSomething();//it will prints out first

similarly whatever the string will be passed to Foo constructor will be printed on calling DoSomething().
Because for example in DoSomething() of above example "this" means fooObject and in do_something_to_a_foo() fooObject is passed by reference.

类似地,任何将传递给 Foo 构造函数的字符串都将在调用 DoSomething() 时打印出来。
因为例如在上面示例的 DoSomething() 中,“this”表示 fooObject 而在 do_something_to_a_foo() 中,fooObject 是通过引用传递的。

回答by Rajat Garg

Acc. to Object Oriented Programming with c++ by Balaguruswamy

累积 Balaguruswamy 使用 c++ 进行面向对象编程

thisis a pointer that points to the object for which thisfunction was called. For example, the function call A.max()will set the pointer thisto the address of the object. The pointer thisis acts as an implicit argument to all the member functions.

this是指向this调用函数的对象的指针。例如,函数调用A.max()将设置指向this对象地址的指针。指针this充当所有成员函数的隐式参数。

You will find a great example of thispointer here. It also helped me to understand the concept. http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/

你会this在这里找到一个很好的指针示例。这也帮助我理解了这个概念。 http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/

回答by Potatoswatter

Nonstatic member functions such as Foo::DoSomethinghave an implicit parameter whose value is used for this. The standard specifies this in C++11 §5.2.2/4:

非静态成员函数,例如Foo::DoSomething具有隐式参数,其值用于this。标准在 C++11 §5.2.2/4 中对此进行了规定:

When a function is called, each parameter (8.3.5) shall be initialized (8.5, 12.8, 12.1) with its corresponding argument. [Note: Such initializations are indeterminately sequenced with respect to each other (1.9) — end note ] If the function is a non-static member function, the thisparameter of the function (9.3.2) shall be initialized with a pointer to the object of the call, converted as if by an explicit type conversion (5.4).

当一个函数被调用时,每个参数(8.3.5)都应该用它对应的参数初始化(8.5、12.8、12.1)。[注意:这样的初始化相对于彼此是不确定的 (1.9) — 尾注 ] 如果函数是非静态成员函数,则函数的this参数 (9.3.2) 应使用指向对象的指针进行初始化调用的,如同通过显式类型转换 (5.4) 进行转换一样。

As a result, you need a Fooobject to call DoSomething. That object simply becomes this.

因此,您需要一个Foo对象来调用DoSomething。该对象简单地变为this.

The only difference (and it's trivial) between the thiskeyword and a normal, explicitly-declared constpointer parameter is that you cannot take the address of this.

this关键字和普通的、显式声明的const指针参数之间的唯一区别(而且很简单)是您不能获取this.

回答by Abhishek Kumar

It is a local pointer.It refers to the current object as local object

它是一个本地指针。它将当前对象称为本地对象