const 成员函数

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 成员函数不能修改调用该函数的对象。因此,函数 avg_price
和函数 same_isbn 只能读取而不能修改调用它们的对象的数据成员。
const 对象、指向 const 对象的指针或引用只能用于调用其
const 成员函数,如果尝试用它们来调用非 const 成员函数,
则是错误的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值