Can you explain the concept of the this pointer? [

2020-08-15 01:47发布

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.

4条回答
相关推荐>>
2楼-- · 2020-08-15 02:03

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.

查看更多
Summer. ? 凉城
3楼-- · 2020-08-15 02:17

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;
}
查看更多
Summer. ? 凉城
4楼-- · 2020-08-15 02:21

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.

查看更多
仙女界的扛把子
5楼-- · 2020-08-15 02:23

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

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 )

查看更多
登录 后发表回答