我需要了解 this
指针的概念,最好附带一个示例。
我是C++的新手,请使用简单的语言,以便我更好地理解。
我需要了解 this
指针的概念,最好附带一个示例。
我是C++的新手,请使用简单的语言,以便我更好地理解。
this
是指向类的实例的指针,并且对所有非静态成员函数可用。
如果您声明了一个类,该类具有私有成员 foo
和方法 bar
,则 foo
可通过 this->foo
在 bar
中使用,但不可通过 instance->foo
对“外部人”使用。
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;
};
因此,this
用于将我们的对象传递给包含的对象。否则,如果没有 this
,我们如何表示我们所在的类?类定义中没有该对象的实例。它是一个类,而不是一个对象。
this
指针会指向你调用该方法的对象。例如,如果你有这个类:class X {
public:
X(int ii) : i(ii) {}
void f();
private:
int i;
void g() {}
};
假设有一个名称为x
的对象,并且您在x
上调用f()
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;
}