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 @   WendellYih  阅读(243)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示