C++对象返回时清除动态数组
我目前正在做一项作业(所以我不想发布完整的代码),试图实现 Bag 抽象数据类型。
下面是我当前正在尝试实现的方法:
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)。然而,当我在退回袋子之前尝试打印出这些元素时,它打印得很好。
毫无疑问,这将是一件微不足道的事情,但我很感激您的帮助。
谢谢。
I'm currently working on an assignment (so I'd rather no post the full code) trying to implement a Bag abstract data type.
Below is a method which I am currently trying to implement:
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;
}
I'm storing the elements as a dynamic array.
My problem is that when the new bag is returned, I can print the cardinality fine (prints to 4, the original bags had two elements each), but the dynamic array doesn't contain the numbers (it prints out some random numbers such as -1789102). However when I try print out the elements before the bag is returned, it prints out fine.
No doubt it will be something trivial, but I'd appreciate the help.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要为您的
Bag
类编写一个复制构造函数。看起来您正在获取默认构造函数,它只对您的类进行浅表复制。这就是为什么基数成员可以,但动态数组却不行。当operator+
函数返回Bag
对象时,将调用复制构造函数。You need to write a copy constructor for your
Bag
class. Looks like you are getting the default constructor which only does a shallow copy of your class. This is why thecardinality
member is ok but your dynamic array is not. The copy constructor is called when youroperator+
function returns theBag
object.