Can you explain the concept of the this pointer? [closed]

∥☆過路亽.° 提交于 2020-01-02 01:11:07

问题


I need to understand this pointer concept, preferably with an example.

I am new to C++, so please use simple language, so that I can understand it better.


回答1:


this is a pointer to an instance of its class and available to all non-static member functions.

If you have declared a class, which has a private member foo and a method bar, foo is available to bar via this->foo but not to "outsiders" via instance->foo.




回答2:


The this pointer is used in a class to refer to itself. It's often handy when returning a reference to itself. Take a look at the proto-typical example using the assignment operator:

class Foo{
public:
    double bar;
    Foo& operator=(const Foo& rhs){
        bar = rhs.bar;
        return *this;
    }
};

Sometimes if things get confusing we might even say

this->bar = rhs.bar;

but it's normally considered overkill in that situation.

Next up, when we're constructing our object but a contained class needs a reference to our object to function:

class Foo{
public:
    Foo(const Bar& aBar) : mBar(aBar){}

    int bounded(){ return mBar.value < 0 ? 0 : mBar.value; }
private:

    const Bar& mBar;
};

class Bar{
public:

      Bar(int val) : mFoo(*this), value(val){}

      int getValue(){ return mFoo.bounded(); }

private:

      int value;
      Foo mFoo;
};

So this is used to pass our object to contained objects. Otherwise, without this how would be signify the class we were inside? There's no instance of the object in the class definition. It's a class, not an object.




回答3:


In object-oriented programming, if you invoke a method on some object, the this pointer points at the object you invoked the method on.

For example, if you have this class

class X {
public:
  X(int ii) : i(ii) {}
  void f();
private:
  int i;
  void g() {}
};

and an object x of it, and you invoke f() on x

x.f();

then within X::f(), this points to x:

void X::f()
{
  this->g();
  std::cout << this->i; // will print the value of x.i
}

Since accessing class members referred to by this is so common, you can omit the this->:

// the same as above
void X::f()
{
  g();
  std::cout << i;
}



回答4:


Pointer is a variable type which points to a another location of your memory. pointers only can hold addresses of memory locations

for example if we say a "int pointer" - > it holds memory address of a int variable

void pointer -> can hold any any type of memory address which is not specific datatype.

& gives the pointed variable ( or the value of the pointer where pointed )



来源:https://stackoverflow.com/questions/4483653/can-you-explain-the-concept-of-the-this-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!