1.何谓this指针
C++primer里定义this指针:指向该类对象的一个指针。成员还是不能定义this指针,但是成员函数可以显式调用this指针。
2.何时用this指针
尽管在成员函数内部显式调用this指针通常是没必要的。但是有一种情况我们是必须这么做:当我们需要将一个对象作为整体引用而不是引用对象的一个成员。所以,在该函数返回对调用该函数的对象的引用时需要this指针。
例如,当一个Screen类有set,move操作。我们希望该类的对象myScreen能使用这样一个表达式:
myScreen.move().set();
这时候就是this指针出场的时候了:
class Screen{
public:
Screen& move(index r,index c);
Screen& set(char);
}
Screen& Screen::set(char c)
{
contents[cursor]=c;
return *this;
}
Screen& Screen::move(index r,index c)
{
index row=r*width;
cursor=row+c;
return *this;
}