转自: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& .