c++ primer 学习笔记:类之隐含的this 指针
来源:互联网 发布:ubuntu永久挂载硬盘 编辑:程序博客网 时间:2024/06/05 00:12
从const 成员函数返回 *this
在普通的非const 成员函数中,this 的类型是一个指向类类型的 const 指针。可以改变this 所指向的值,但不能改变 this 所保存的地址。在 const 成员函数中,this 的类型是一个指向 const 类类型对象的 const 指针。既不能改变 this 所指向的对象,也不能改变 this 所保存的地址。
不能从const 成员函数返回指向类对象的普通引用。const 成员函数只能返回 *this 作为一个 const 引用。
基于const 的重载
基于成员函数是否为const,可以重载一个成员函数;同样地,基于一个指针形参是否指向const,可以重载一个函数。const 对象只能使用 const 成员。非 const 对象可以使用任一成员,但非 const 版本是一个更好的匹配。
在此,我们将定义一个名为do_display 的 private 成员来打印 Screen。每个display 操作都将调用此函数,然后返回调用自己的那个对象:
class Screen {public: // interface member functions // display overloaded on whether the object is const or not Screen& display(std::ostream &os) { do_display(os); return *this; } const Screen& display(std::ostream &os) const { do_display(os); return *this; }private: // single function to do the work of displaying a Screen, // will be called by the display operations void do_display(std::ostream &os) const { os << contents; } // as before};现在,当我们将display 嵌入到一个长表达式中时,将调用非 const 版本。当我们 display 一个 const 对象时,就调用 const 版本:
Screen myScreen(5,3);const Screen blank(5, 3);myScreen.set('#').display(cout); // calls nonconst versionblank.display(cout); // calls const version
可变数据成员
有时(但不是很经常),我们希望类的数据成员(甚至在const 成员函数内)可以修改。这可以通过将它们声明为 mutable 来实现。可变数据成员(mutable data member)永远都不能为const,甚至当它是const 对象的成员时也如此。因此,const 成员函数可以改变 mutable 成员。要将数据成员声明为可变的,必须将关键字mutable 放在成员声明之前:
class Screen {public:// interface member functionsprivate:mutable size_t access_ctr; // may change in a const members// other data members as before};
- c++ primer 学习笔记:类之隐含的this 指针
- C++Primer学习-类(隐含的this指针)
- c++ primer 学习笔记21类的定义和声明、隐含的this指针、类作用域
- c++primer 3/7--类作用域,隐含的 this 指针
- 【C++】隐含的this指针
- 隐含的 this 指针
- 隐含的this指针
- 隐含的this指针
- C++隐含的this指针
- 12.2隐含的this指针
- C++primer 指针学习笔记
- C++ Primer 学习笔记_49_类与数据抽象 -暗含的this指针
- 【C++】【学习笔记】【016】this指针和类的继承
- C++Primer 学习笔记之指针和引用
- 类中函数的一个隐含参数--this指针
- c++primer学习笔记(4.2)指针的引入
- 成员函数隐含的this指针
- 成员函数隐含的this指针
- 游戏程序员具备
- 缓存设计,LIRS,cache锁粒度
- 电平柱状动态图
- 关于KMP算法当中的next函数
- Mac系统下Android SDK更新以及ADT无法在线下载
- c++ primer 学习笔记:类之隐含的this 指针
- 2013 吉林通化邀请赛 Tutor 有点坑的水题
- 你还不知道的sizeof()
- mvc action 有多种跳转
- 【读书笔记】《怪诞行为学》丹·艾瑞里
- Goautodial vtigerCrm 客户管理
- java循环控制中break、continue、return的比较
- Java的I/O流
- HDU 4700 flow Gomory–Hu tree,通过已知最大流构造图形