const成员函数

转自:Prime C++

在类Sales_item中,same_isbn函数定义如下: 

bool Sales_item::same_isbn(const Sales_item &rhs) const 
     { return isbn == rhs.isbn; }

 const 成员函数的引入

跟在 Sales_item 成员函数声明的形参表后面的 const 所起的作用了:const 改变了隐含的this 形参的类型。在调用total.same_isbn(trans) 时,隐含的 this 形参将是一个指向total 对象的 const Sales_Item* 类型的指针。就像如下编写 same_isbn 的函数体一样:

// pseudo-code illustration of how the implicit this pointer is used
// This code is illegal: We may not explicitly define the this pointer ourselves
// Note that this is a pointer to const because same_isbn is a const member
bool Sales_item::same_isbn(const Sales_item *const this,const Sales_item &rhs) const
     { return (this->isbn == rhs.isbn); }

用这种方式使用 const 的函数称为常量成员函数。由于this 是指向const 对象的指针,const 成员函数不能修改调用该函数的对象。因此,函数 same_isbn 只能读取而不能修改调用它们的对象的数据成员。

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
      };
在函数const Screen& display(std::ostream &os) const中,由于this指针的类型为const Sales_item *const 所以,return *this时,函数的返回值类型必须为const Screen& .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值