你能解释一下这个指针的概念吗?

Tru*_*pti 9 c++ this this-pointer

我需要理解this指针概念,最好用一个例子.

我是C++的新手,所以请使用简单的语言,以便我能更好地理解它.

Lin*_*een 6

this 是指向其类实例的指针,可用于所有非静态成员函数.

如果您声明了一个具有私有成员foo和方法的类bar,foo则可以bar通过this->foo但不能通过"外部人员"进行通过instance->foo.


whe*_*ies 6

this指针是一类用来指本身.返回对自身的引用时通常很方便.使用赋值运算符查看原始典型示例:

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

有时如果事情变得混乱,我们甚至会说

this->bar = rhs.bar;
Run Code Online (Sandbox Code Playgroud)

但在这种情况下通常被视为过度杀伤.

接下来,当我们构造我们的对象时,包含的类需要引用我们的对象来运行:

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;
};
Run Code Online (Sandbox Code Playgroud)

因此this用于将我们的对象传递给包含的对象.否则,没有this如何表示我们在里面的课程?类定义中没有对象的实例.这是一个阶级,而不是一个对象.