this与const

在普通非const成员函数中,this是const指针,而在const成员函数中,this是const对象的const指针。

 1 class Foo
 2 {
 3     Foo& get_self1(void)
 4     {
 5         return *this;           // Foo * const this;
 6     }
 7     
 8     const Foo& get_self2(void)
 9     {
10         return *this;           // const Foo * const this;
11     }
12 };

 所以往往返回const引用的成员函数需要重载,不然这个函数无法用于某些表达式,

MyFoo.get_self2().set();

这条语句显然是非法的!

posted @ 2014-10-10 20:11  WendellYih  阅读(237)  评论(0编辑  收藏  举报