2009年7月30日 星期四

What is a "const member function"?

class Fred {
public:
void inspect() const;
// This member promises NOT to change *this
void mutate();
// This member function might change *this
};

void userCode(Fred& changeable, const Fred& unchangeable)
{
changeable.inspect();
// OK: doesn't change a changeable object
changeable.mutate();
// OK: changes a changeable object

unchangeable.inspect();
// OK: doesn't change an unchangeable object
unchangeable.mutate();
// ERROR: attempt to change unchangeable object

}


The trailing const on inspect() member function means that the abstract (client-visible) state of the object (the member varible) isn't going to change.(一般來說gtter method會宣告成const)

There is a possibility to modify members of an object even from a const function though: you can declare members "mutable". This can be usefull if you need to modify the way the data is represented internally without modifying it's meaning. (若有一個member varible 被宣告成mutable,則const member function 可以改變這一個varible)

class Ball {
mutable double radius;
int color;
public:
double getMoreRadius() const {
return radius++;
}
// ....
};

reference:
http://home.wanadoo.nl/efx/c++-faq/const-correctness.html
http://www.hala.bz/read.php?tid=7151&toread=1&fpage=1
http://lists.trolltech.com/qt-interest/2006-01/msg00563.html

沒有留言: