一、const member functions(const成员函数)

例子:const String str("hello world");
str.print();
如果当初设计String::print()时未指明const,那么上行便是经由const object调用non-const member function,会出错。此非吾人所愿

二.const成员函数重载
当成员函数的const和non-const版本同时存在,const object只能调用const版本,non-const object只能调用non-const版本;
class template std::basic_string<…> 有如下两个member functions:
charT operator[](size_type pos) const {
/不必考虑 Copy on Write /
}
reference operator[](size_type pos) {
/必须考虑 Copy on Write /
}
COW:Copy on Write
const string s1("hello world"); cout << s1[0]; // 调用const版本
string s2("hello world"); s2[0] = "t"; // 调用非const版本
三.总结
1. const修饰的成员函数,不仅限制函数去修改成员变量,同时也可以实现函数的重载
2. const修饰的成员函数,如果没有被重载,那么非const对象和const对象都可以调用;
3. const修饰的成员函数,如果被重载了,非const对象只能调用没有被const修饰的成员函数,const对象也只能调用被const修饰的成员函数。

2125

被折叠的 条评论
为什么被折叠?



