14

我需要了解this指针的概念,最好举个例子。

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

4

4 回答 4

9

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

如果您声明了一个具有私有成员foo和方法的类bar,则对viafoo可用,但对“局外人” via 不可用。barthis->fooinstance->foo

于 2010-12-19T15:40:12.877 回答
6

指针在this类中用于引用自身。返回对自身的引用时,它通常很方便。看一下使用赋值运算符的原型示例:

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

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

this->bar = rhs.bar;

但在这种情况下,它通常被认为是矫枉过正。

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

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;
};

Sothis用于将我们的对象传递给包含的对象。否则,如果没有this,我们所在的班级将如何表示?类定义中没有对象的实例。它是一个类,而不是一个对象。

于 2010-12-19T15:43:44.860 回答
3

在面向对象编程中,如果您调用某个对象的方法,则this指针指向您调用该方法的对象。

例如,如果你有这个类

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

和它的一个对象x,然后你f()调用x

x.f();

然后在X::f(),this指向x

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

由于访问引用的类成员this非常普遍,您可以省略this->

// the same as above
void X::f()
{
  g();
  std::cout << i;
}
于 2010-12-19T15:53:34.033 回答
1

指针是一种变量类型,它指向程序内存中的另一个位置指针只能保存内存位置的地址

图片

例如,如果我们说“int 指针”-> 它保存int变量的内存地址。

"void pointer" -> 可以保存任何类型的内存地址,它不是特定的数据类型。

&运算符给出变量的地址(或指向的指针的值)。

于 2010-12-19T15:47:10.050 回答