de *_*sto 16 c++ pointers this
this
关键字的目的是什么?类中的方法是否可以访问同一个类中的其他对等成员?this
在类中调用一个调用peer方法的需要是什么?
Jos*_*ley 35
两个主要用途:
将*this
或this
作为参数传递给其他非类方法.
void do_something_to_a_foo(Foo *foo_instance);
void Foo::DoSomething()
{
do_something_to_a_foo(this);
}
Run Code Online (Sandbox Code Playgroud)MessageBox::MessageBox(const string& message)
{
this->message = message;
}
Run Code Online (Sandbox Code Playgroud)
(虽然在这个特定的例子中,初始化列表通常比分配更好.)Mar*_*ork 14
例:
struct A
{
void test(int x)
{
this->x = x; // Disambiguate. Show shadowed variable.
}
A& operator=(A const& copy)
{
x = copy.x;
return *this; // return a reference to self
}
bool operator==(A const& rhs) const
{
return isEqual(*this, rhs); // Pass yourself as parameter.
// Bad example but you can see what I mean.
}
private:
int x;
};
Run Code Online (Sandbox Code Playgroud)