我需要了解this
指针的概念,最好举个例子。
我是 C++ 新手,所以请使用简单的语言,以便我更好地理解它。
this
是指向其类实例的指针,可用于所有非静态成员函数。
如果您声明了一个具有私有成员foo
和方法的类bar
,则对viafoo
可用,但对“局外人” via 不可用。bar
this->foo
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;
};
Sothis
用于将我们的对象传递给包含的对象。否则,如果没有this
,我们所在的班级将如何表示?类定义中没有对象的实例。它是一个类,而不是一个对象。
在面向对象编程中,如果您调用某个对象的方法,则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;
}