0
我目前工作的一個任務(所以我寧願不交的全部代碼)試圖執行一個袋子抽象數據類型。C++動態數組時清除對象返回
下面是我目前想實現的方法:
template <typename T>
Bag<T> Bag<T>::operator+ (const Bag<T>& bag) {
int sizeofCurrentMultiset = cardinality_;
int sizeofPassedMultiset = bag.cardinality_;
int totalSize = sizeofCurrentMultiset + sizeofPassedMultiset;
Bag<T> newBag(totalSize);
for (int i = 0; i < sizeofCurrentMultiset; i++) {
newBag.insert(array_[i]);
}
for (int i = 0; i < sizeofPassedMultiset; i++) {
newBag.insert(bag.array_[i]);
}
return newBag;
}
我存儲的元素爲動態數組。
我的問題是,當新的包被退回時,我可以打印基數罰款(打印到4,原始袋每個都有兩個元素),但動態數組不包含數字(打印出一些隨機數如-1789102)。但是,當我在包退回之前嘗試打印元素時,它會打印出正常。
毫無疑問,這將是一些小事,但我欣賞的幫助。
謝謝。
此代碼看起來不錯。問題可能在於你的'insert'方法,或者如果'insert'使用複製語義,可能在你的拷貝構造函數中。 –
您可以發佈用於打印所有內容的代碼嗎? – Mythli
你是否爲'Bag'寫過一個拷貝構造函數?聽起來你可能會得到默認的拷貝構造函數。 –