c++ primer 学习笔记:类之隐含的this 指针

从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 version
blank.display(cout); // calls const version

可变数据成员

有时(但不是很经常),我们希望类的数据成员(甚至在const 成员函数内)可以修改。这可以通过将它们声明为 mutable 来实现。
可变数据成员(mutable data member)永远都不能为const,甚至当它是const 对象的成员时也如此。因此,const 成员函数可以改变 mutable 成员。要将数据成员声明为可变的,必须将关键字mutable 放在成员声明之前:
class Screen {
public:
// interface member functions
private:
mutable size_t access_ctr; // may change in a const members
// other data members as before
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值