我们都知道const成员函数只能调用非const成员函数
但是有的时候,我们为了代码复用
例如:
T operator[](int i) const;
T& operator[](int i);
为了实现const和非const两个版本,我们选择使用重载,但是里面的内容可能是相同的,为了代码复用可以:
T& operator[](int i) {
if( (i >= 0) && (i < m_length) ) {
return m_array[i];
}
else {
THROW_EXCEPTION(IndexOutOfBoundsException, "T& operator[](int i) i");
}
}
T operator[](int i) const{
return const_cast<SeqList&>(*this)[i];
}
使用 const_cast<SeqList&>(this),把const版本的this转化为非const然后调用非const版本的[],因为const只在编译期,在运行期是不存在const的