我們都知道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的