我有一個關於const函數的問題:const函數可以在函數的本地對象上調用非const函數嗎?以下是我正在談論的一個示例:const函數可以在本地對象上調用非const函數嗎?
template <class T>
Set<T> Set<T>::setUnion (const Set<T> & other) const
{
Set<T> unionSet; //create union set
unionSet.merge(internalStorage); //merge it with our current set
unionSet.merge(other.internalStorage); //merge it with other set, duplicates will not be added
return unionSet;
}
此函數帶兩組並返回集合的並集。但問題在於合併函數不是const,並且合併函數也調用了也不是const的add函數,所以我看不到任何其他方式創建一個只有這兩個函數的聯合集,因爲setUnion函數必須是const。
PS:我知道解決方案沒有做一個const函數,我這樣做的原因是因爲我的教授定義它是這樣的。謝謝。
例外:'mutable'成員。 – Deduplicator 2014-09-26 21:32:41
@Deduplicator:的確,「const」的含義有許多細微差別,與這個問題無關。相關的一點是,它不會阻止修改除'* this'之外的任何內容。 – 2014-09-26 22:17:24