隐含的 this 指针
成员函数具有一个附加的隐含形参,即指向该类对象的一个指针。这个隐含形参命名为 this,与调用成员函数的对象绑定在一起。成员函数不能定义 this 形参,而是由编译器隐含地定义。成员函数的函数体可以显式使用 this 指针,但不是必须这么做。如果对类成员的引用没有限定,编译器会将这种引用处理成通过 this 指针的引用。
何时使用 this 指针
尽管在成员函数内部显式引用 this 通常是不必要的,但有一种情况下必须这样做:当我们需要将一个对象作为整体引用而不是引用对象的一个成员时。最常见的情况是在这样的函数中使用 this:该函数返回对调用该函数的对象的引用。
返回 *this
set 操作,将特定字符或光标指向的字符设置为给定值。
move 操作,给定两个 index 值,将光标移至新位置。
class Screen {
public:
// interface member functions
Screen& move(index r, index c);
Screen& set(char);
// other members as before
};
注意,这些函数的返回类型是 Screen&,指明该成员函数返回对其自身类类型的对象的引用。每个函数都返回调用自己的那个对象。使用 this 指针来访问该对象。
Screen& Screen::set(char c)
{
contents[cursor] = c;
return *this;
}
Screen& Screen::move(index r, index c)
{
index row = r * width; // row location
cursor = row + c;
return *this;
}
在这些函数中,this 是一个指向非常量 Screen 的指针。如同任意的指针一样,可以通过对 this 指针解引用来访问 this 指向的对象。
从 const 成员函数返回 *this
在普通的非 const 成员函数中,this 的类型是一个指向类类型的 const指针。可以改变 this 所指向的值,但不能改变 this 所保存的地址。在 const 成员函数中,this 的类型是一个指向 const 类类型对象的const 指针。既不能改变 this 所指向的对象, 也不能改变 this 所保存的地址。
不能从 const 成员函数返回指向类对象的普通引用。const 成员函数只能返回 *this 作为一个 const 引用。
可以给 Screen 类增加一个 display 操作。这个函数应该在给定的 ostream 上打印 contents。逻辑上,这个操作应该是一个 const 成员。打印 contents 不会改变对象。如果将 display 作为 Screen 的 const 成员,则 display 内部的 this 指针将是一个 const Screen* 型的 const。
我们希望能够在一个操作序列中使用display:
// move cursor to given position, set that character and display the screen
myScreen.move(4,0).set('#').display(cout);
这个用法暗示了 display 应该返回一个 Screen 引用,并接受一个ostream 引用。如果 display 是一个 const 成员,则它的返回类型必须是const Screen&。
不幸的是,这个设计存在一个问题。如果将 display 定义为 const 成员,就可以在非 const 对象上调用 display, 但不能将对 display 的调用嵌入到一个长表达式中。下面的代码将是非法的:
Screen myScreen;
// this code fails if display is a const member function
// display return a const reference; we cannot call set on a const
myScreen.display().set('*');
问题在于这个表达式是在由 display 返回的对象上运行 set。该对象是const,因为 display 将其对象作为 const 返回。我们不能在 const 对象上调用 set。

浙公网安备 33010602011771号